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.
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.
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.
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.
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]]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With