Python: slicing a multi-dimensional array

Python Programming

Question or problem about Python programming:

I’m new to Python and numpy. I’ve figured out how to slice 1 dimensional sequence: arr[start:end], and access an element in the array: el = arr[row][col].

Trying something like slice = arr[0:2][0:2] (where arr is a numpy array) doesn’t give me the first 2 rows and columns, but repeats the first 2 rows. What did I just do, and how do I slice along another dimension?

How to solve the problem:

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0’s,

slice = arr[0:2,0:2]

You’ll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different “name”.


Another way, if you’re working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0’s here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I’m building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you’re just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the “native” solution I posted above.

Hope this helps!