I need to slice a list of lists in python.
A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
idx = slice(0,4)
B = A[:][idx]
The code above isn't giving me the right output.
What I want is : [[1,2,3],[1,2,3],[1,2,3]]
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.
List slicing returns a new list from the existing list.
It's possible to "slice" a list in Python. This will return a specific segment of a given list. For example, the command myList[2] will return the 3rd item in your list (remember that Python begins counting with the number 0).
In Python, by using a slice (e.g.: [2:5:2] ), you can extract a subsequence of a sequence object, such as a list, string, tuple, etc.
Very rarely using slice objects is easier to read than employing a list comprehension, and this is not one of those cases.
>>> A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
>>> [sublist[:3] for sublist in A]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
This is very clear. For every sublist in A
, give me the list of the first three elements.
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