Skip to content
Advertisement

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

Creating a 2D array such as

JavaScript

and indexing using the colon operator like this

JavaScript

works as expected. It returns all of row 2.

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

JavaScript

But this also returns

JavaScript

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)

Advertisement

Answer

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

JavaScript

is

JavaScript

Similarly,

JavaScript

is

JavaScript

in effect both just mean

JavaScript

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).

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