Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing Nested List

Tags:

I'm familiar with slicing, I just can't wrap my head around this, and I've tried changing some of the values to try and illustrate what's going on, but it makes no sense to me.

Anyway, here's the example:

l = [[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]]  
print l[:,0:2]

Resulting in:

[[0, 0], [0, 1] [1, 0], [1, 1]]

I'm trying to translate this as "slice from index 0 to 0,2, incrementing by 2" which makes no sense to me.

like image 786
prelic Avatar asked Mar 18 '11 01:03

prelic


People also ask

What is nested list in Python?

A nested list is a list of lists, or any list that has another list as an element (a sublist). They can be helpful if you want to create a matrix or need to store a sublist along with other data types.

How do you extract an element from a nested list in Python?

Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the 'lst' as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.

How do you slice a 2d list in Python?

As shown in the above syntax, to slice a Python list, you have to append square brackets in front of the list name. Inside square brackets you have to specify the index of the item where you want to start slicing your list and the index + 1 for the item where you want to end slicing.


2 Answers

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.

like image 85
GWW Avatar answered Oct 18 '22 21:10

GWW


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]]
>>> 
like image 28
JC Cheloven Avatar answered Oct 18 '22 20:10

JC Cheloven