4

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!

Michael
  • 8,920
  • 3
  • 38
  • 56
user124123
  • 1,642
  • 7
  • 30
  • 50
  • 4
    Googling `list slicing python comma` works. Just mentioning it because you mentioned the difficulties of searching for this. – keyser Jul 26 '13 at 13:14
  • This is a weird example, if the variable `list` is a multidimensional numpy array (as Martijn suggests) the last bit `for i in range(0,list)` doesn't make sense. Also having a variable called `list` is bad because it hides the Python `list` function... – Jan Kuiken Jul 26 '13 at 13:38

2 Answers2

11

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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.

>>> 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)
>>>
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • +1, this shows that objects other than numpy array's can be indexed with a tuple (note that the OP did not include the numpy tag). Still this `x` results in an error with `for i in range(0,x)`. OP should post some more of the code he/she was reading... – Jan Kuiken Jul 26 '13 at 17:29