Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slicing list of lists in Python

Tags:

python

list

slice

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]]

like image 843
HuckleberryFinn Avatar asked Apr 05 '16 20:04

HuckleberryFinn


People also ask

Can you slice a list of lists 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.

Does slicing a list create a new list?

List slicing returns a new list from the existing list.

What is list slicing in Python with example?

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

Can you splice a list in Python?

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.


1 Answers

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.

like image 167
timgeb Avatar answered Sep 30 '22 15:09

timgeb