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

JavaScript

and getting back something like

JavaScript

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

JavaScript

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

JavaScript

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

JavaScript

or

JavaScript

? (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:

JavaScript

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:

JavaScript

Output:

JavaScript

Try it here.

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