Unpacking tuples/arrays/lists as indices for Numpy Arrays

Posted on

Question :

Unpacking tuples/arrays/lists as indices for Numpy Arrays

I would love to be able to do

>>> A = numpy.array(((1,2),(3,4)))
>>> idx = (0,0)
>>> A[*idx]

and get


however this is not valid syntax. Is there a way of doing this without explicitly writing out

>>> A[idx[0], idx[1]]


EDIT: Thanks for the replies. In my program I was indexing with a Numpy array rather than a tuple and getting strange results. Converting to a tuple as Alok suggests does the trick.

Asked By: ntimes


Answer #1:

It’s easier than you think:

>>> import numpy
>>> A = numpy.array(((1,2),(3,4)))
>>> idx = (0,0)
>>> A[idx]
Answered By: ntimes

Answer #2:



Unless you have a more complex use case that’s not as simple as this example, the above should work for all arrays.

Answered By: Vicki Laidler

Answer #3:

No unpacking is necessary—when you have a comma between [ and ], you are making a tuple, not passing arguments. foo[bar, baz] is equivalent to foo[(bar, baz)]. So if you have a tuple t = bar, baz you would simply say foo[t].

Answered By: Alok Singhal

Answer #4:

Indexing an object calls:


When you do A[1, 2], it’s the equivalent of:

A.__getitem__((1, 2))

So when you do:

b = (1, 2)

A[1, 2] == A[b]
A[1, 2] == A[(1, 2)]

Both statements will evaluate to True.

If you happen to index with a list, it might not index the same, as [1, 2] != (1, 2)

Answered By: Mike Graham

Leave a Reply

Your email address will not be published. Required fields are marked *