Skip to content
Advertisement

Access multiple elements of list knowing their index [duplicate]

I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:

JavaScript

Is there any better way to do it? something like c = a[b] ?

Advertisement

Answer

You can use operator.itemgetter:

JavaScript

Or you can use numpy:

JavaScript

But really, your current solution is fine. It’s probably the neatest out of all of them.

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