"[:,]" list slicing python, what does it mean?

Question:

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!

Asked By: user124123

||

Answers:

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.

Answered By: Martijn Pieters

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)
>>>
Answered By: tdelaney
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.