0

I can use an array or a list to index into numpy.array, e.g.:

a = np.array([1, 2, 3, 4])
print(a[[1, 3]])

will produce

[2 4]

Is there an equivalent construct to index into a standard Python list or array?

Just to be more specific: indexing has to be with an array and indexing pattern is random, i.e. not possible with slicing. Here is a better example:

a = np.array([1, 2, 3, 4])
i = [3, 0, 1]
print(a[i])
.....
[4 1 2]
7
  • 1
    I don't think so, that is the reason why we use NumPy. Commented Nov 17, 2021 at 5:08
  • 2
    It depends on what you mean by equivalent. [my_list[i] for i in index_list] would give such result. Commented Nov 17, 2021 at 5:11
  • No, there isn't. Commented Nov 17, 2021 at 5:28
  • 1
    In this specific case a slice would do. But you are probably not just looking for evenly spaced indices, do you? Commented Nov 17, 2021 at 5:34
  • @MisterMiyagi No. I'm looking for a general case. Commented Nov 17, 2021 at 5:39

1 Answer 1

1
from operator import itemgetter 

print(itemgetter(1,3)(a))

and to turn it into a list:

print(list(itemgetter(1,3)(a)))
Sign up to request clarification or add additional context in comments.

2 Comments

Which is implemented as an iteration on the indices: tuple(obj[i] for i in items)
Not quite there, since it indexes with and produces a tuple not an array.

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.