Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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!

like image 237
user124123 Avatar asked Dec 11 '22 12:12

user124123


2 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.

like image 195
Martijn Pieters Avatar answered Jan 01 '23 21:01

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)
>>>
like image 38
tdelaney Avatar answered Jan 01 '23 20:01

tdelaney