Slicing list of lists in Python

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.

Leave a Comment