user124123
user124123

Reputation: 1683

"[:,]" 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 punctuation.

Any help greatly appreciated!

Upvotes: 4

Views: 1555

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125398

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.

Upvotes: 11

tdelaney
tdelaney

Reputation: 77407

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.

>>> class X(object):
...     def __getitem__(self, name):
...             print type(name),name
...
>>> x=X()
>>> x[:,2]
<type 'tuple'> (slice(None, None, None), 2)
>>> x[1,2,3,4]
<type 'tuple'> (1, 2, 3, 4)
>>>

Upvotes: 2

Related Questions