slicing list of lists in Python

A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]

print [a[:3] for a in A]

Using list comprehension


With numpy it is very simple - you could just perform the slice:

In [1]: import numpy as np

In [2]: A = np.array([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]])

In [3]: A[:,:3]
Out[3]: 
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])

You could, of course, transform numpy.array back to the list:

In [4]: A[:,:3].tolist()
Out[4]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

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.


you can use a list comprehension such as: [x[0:i] for x in A] where i is 1,2,3 etc based on how many elements you need.

Tags:

Python

List

Slice