'How to slice a nested list twice?

With a nested list like:

ex_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I need to be able to slice this list for:

[[1, 2], [4, 5]]

I've been trying:

list(ex_list[:2][:2])

but this isn't working. I'm obviously doing something very wrong but haven't been able to find a solution as using commas doesn't work either for some reason.



Solution 1:[1]

You should try using comprehension: Try:

[i[:2] for i in ex_list[:2]]

Code:

ex_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([i[:2] for i in ex_list[:2]])

Output:

[[1, 2], [4, 5]]

Solution 2:[2]

You need to slice the elements separately to the outer list; it's better to do the outer list first to avoid unnecessary inner slices.

[inner[:2] for inner in ex_list[:2]]

Solution 3:[3]

Is using numpy an option?

import numpy as np

ex_list = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(ex_list[:2,:2].tolist()) # [[1, 2], [4, 5]]

The first :2 slice the outer list, the second slice each one of the inner lists.

Solution 4:[4]

You can try map

l = list(map(lambda lst: lst[:2], ex_list))
print(l)

[[1, 2], [4, 5], [7, 8]]

Or with itemgetter

from operator import itemgetter

l = list(map(itemgetter(slice(0,2)), ex_list))
print(l)

[[1, 2], [4, 5], [7, 8]]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jeff Schaller
Solution 3 Guy
Solution 4 Ynjxsjmh