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[:] [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
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)
The reason is that
[:] just means “everything”, and that the two indexing operations in a row are completely independent.
y = x[:]
tmp = x y = tmp[:] # this only makes a copy, does nothing else
y = x[:]
tmp = x[:] # this only makes a copy, does nothing else y = tmp
in effect both just mean
y = x
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).