I have a list l=[[[1,2,3],[4,5,6]],[[7,8,9],[9,1,2]]]
How do I get the list [[[1,2],[4,5]],[[7,8],[9,1]]]
using just slicing? I tried l[:][:][:2]
but it gave me the entire 3d list.
Asked
Active
Viewed 116 times
2

vaultah
- 44,105
- 12
- 114
- 143

Hari Narayan
- 21
- 1
-
Possible duplicate of [Python: slicing a multi-dimensional array](https://stackoverflow.com/questions/17277100/python-slicing-a-multi-dimensional-array) – GalAbra Mar 03 '18 at 17:23
2 Answers
1
You could use a nested list comprehension, of course this ins't only using slicing but hopefully still useful:
>>> lst = [[[1,2,3],[4,5,6]],[[7,8,9],[9,1,2]]]
>>> [[subsub[:-1] for subsub in sublist] for sublist in lst]
[[[1, 2], [4, 5]], [[7, 8], [9, 1]]]

Chris_Rands
- 38,994
- 14
- 83
- 119
-
I would point out that it is actually not possible with only slicing. – Olivier Melançon Mar 03 '18 at 17:23
1
Update: just noticed your outer lists do not need slicing. In that case:
Since you are on Python2 map
works well on this one:
>>> from operator import itemgetter
>>> ft = itemgetter(slice(2))
>>>
>>> map(map, (ft, ft), l)
[[[1, 2], [4, 5]], [[7, 8], [9, 1]]]
The solution below was wrongly assuming the input list was 3 x 3 x 3
and to be sliced to 2 x 2 x 2
. I'll leave it here in case anybody is looking for that case.
>>> from operator import itemgetter
>>> ft = itemgetter(slice(2))
>>>
>>> map(map, (ft, ft), map(ft, l[:2]))
[[[1, 2], [4, 5]], [[7, 8], [9, 1]]]

Paul Panzer
- 51,835
- 3
- 54
- 99