Why doesn’t the Python 2D array index order matter when used with colon ( : )

Why doesn’t the Python 2D array index order matter when used with colon ( : )

Creating a 2D array such as

x = [range(i, i+10) for i in xrange(1,100,10)]

and indexing using the colon operator like this

>>> x[2][:]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

works as expected. It returns all of row 2.

However, if I want to retrieve all of column 2, I would instinctively do

>>> x[:][2]

But this also returns

[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]

What is the reasoning behind this? I would intuitively think that this returns the column 2 of each row.

(Also, I am aware I can use numpy to do x[:,2] or I could use list comprehensions to accomplish this, that’s not my question)

Best answer

The reason is that [:] just means “everything”, and that the two indexing operations in a row are completely independent.

y = x[2][:]

is

tmp = x[2]
y = tmp[:]  # this only makes a copy, does nothing else

Similarly,

y = x[:][2]

is

tmp = x[:]  # this only makes a copy, does nothing else
y = tmp[2]

in effect both just mean

y = x[2]

There is no 2D indexing going on at any point, Python doesn’t have 2D indexing (although numpy has hacks that make it work like there is actual 2D indexing going on).