31

I would love to be able to do

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

and get

1

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.

2
  • It was a tough call. In the end I thought Vicki could do with the points more than you. Still gave you an upvote though :-) Commented Mar 15, 2010 at 22:46
  • Also, I guess Vicki's answer illustrates that I can use the example tuple directly. Commented Mar 15, 2010 at 22:47

4 Answers 4

26

It's easier than you think:

>>> import numpy
>>> A = numpy.array(((1,2),(3,4)))
>>> idx = (0,0)
>>> A[idx]
1
Sign up to request clarification or add additional context in comments.

1 Comment

it is due to the difference between tuples and arrays
22

Try

A[tuple(idx)]

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

2 Comments

@Mike: yes, but the question title says it might be a list or an array.
Works for Pytorch too.
6

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

Comments

4

Indexing an object calls:

object.__getitem__(index)

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.