2

I'm new to python and wanted to do something I normally do in matlab/R all the time, but couldn't figure it out from the docs.

I'd like to slice an array not as 0:3 which includes elements 0,1,2 but as an explicit vector of indices such as 0,3 For example, say I had this data structure

a = [1, 2, 3, 4, 5]

I'd like the second and third element so I thought something like this would work

a[list(1,3)]

but that gives me this error

TypeError: list indices must be integers

This happens for most other data types as well such as numpy arrays

In matlab, you could even say a[list(2,1)] which would return this second and then the first element.

There is an alternative implementation I am considering, but I think it would be slow for large arrays. At least it would be damn slow in matlab. I'm primarily using numpy arrays.

[ a[i] for i in [1,3] ]

What's the python way oh wise ones? Thanks!!

2 Answers 2

1

NumPy allows you to use lists as indices:

import numpy
a = numpy.array([1, 2, 3, 4, 5])
a[[1, 3]]

Note that this makes a copy instead of a view.

Sign up to request clarification or add additional context in comments.

Comments

1

I believe you want numpy.take:

newA = numpy.take(a, [1,3])

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.