Slicing Nested List

What you are doing is basically multi-axis slicing. Because l is a two dimensional list and you wish to slice the second dimension you use a comma to indicate the next dimension.

the , 0:2 selects the first two elements of the second dimension.

There's a really nice explanation here. I remember it clarifying things well when I first learned about it.


Works as said for me only if 'l' is a numpy array. For 'l' as regular list it raises an error (Python 3.6):

>>> l
[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]]
>>> print (l[:,0:2])

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not tuple

>>> l=np.array(l)
>>> l
array([[0, 0, 0],
       [0, 1, 0],
       [1, 0, 0],
       [1, 1, 1]])
>>> print (l[:,0:2])
[[0 0]
 [0 1]
 [1 0]
 [1 1]]
>>>