Skip to content Skip to sidebar Skip to footer

"[:,]" List Slicing Python, What Does It Mean?

I'm reading some code and I see ' list[:,i] for i in range(0,list))......' I am mystified as to what comma is doing in there, :, and google offers no answers as you cant google pun

Solution 1:

You are looking at numpy multidimensional array slicing.

The comma marks a tuple, read it as [(:, i)], which numpy arrays interpret as: first dimension to be sliced end-to-end (all rows) with :, then for each row, i selects one column.

See Indexing, Slicing and Iterating in the numpy tutorial.

Solution 2:

Not trying to poach Martijn's answer, but I was puzzled by this also so wrote myself a little getitem explorer that shows what's going on. Python gives a slice object to getitem that objects can decide what to do with. Multidimensional arrays are tuples too.

>>>classX(object):...def__getitem__(self, name):...printtype(name),name...>>>x=X()>>>x[:,2]
<type 'tuple'> (slice(None, None, None), 2)
>>>x[1,2,3,4]
<type 'tuple'> (1, 2, 3, 4)
>>>

Post a Comment for ""[:,]" List Slicing Python, What Does It Mean?"