Skip to content
Advertisement

Why don’t Multi-dimensional (non-numpy) list slices work (anymore?)

Didn’t we used to…

I remember being able to type in something like

>>> mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> myslice = slice(1,3)
>>> mylist[myslice, myslice]

and getting back something like

[[5, 6], [8, 9]]

If I type the code above, I will get the following error (in Python 3.7):

TypeError: list indices must be integers or slices, not tuple

But if I call just one dimension, it works fine:

>>> mylist[myslice]
[[4, 5, 6], [7, 8, 9]]

What’s the Direct, Easy Slice Syntax?

While I’m mildly interested if things changed or if I am just going crazy, I mostly want to know how I can do multi-dimensional slicing. What is the correct syntax instead of

>>> mylist[myslice, myslice]

or

>>> mylist[myslice][myslice]

? (The second one does not raise an error, but it does not work. It returns [7, 8, 9].)

I know I can do list comprehensions, use numpy, or other “workarounds”. But how can a slice be used directly for multiple dimensions? If I want just one element, the syntax works fine:

>>> mylist[1][1]

But this will not work for slices…

Advertisement

Answer

I think the easiest way to do this in plain python is by using a list comprehension:

myslice = slice(1,3)
mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
sliced = [partSlice[myslice] for partSlice in mylist[myslice]]
print(sliced)

Output:

[[5, 6], [8, 9]]

Try it here.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement