cjg123
cjg123

Reputation: 473

Python: How to get the nth element from list, where n is from a list

So say I have:

a = ['the dog', 'cat', 'the frog went', '3452', 'empty', 'animal']
b = [0, 2, 4]

How can I return:

c = ['the dog', 'the frog went', 'empty'] ?

i.e how can I return the nth element from a, where n is contained in a separate list?

Upvotes: 1

Views: 2705

Answers (4)

iGian
iGian

Reputation: 11183

Other option, list comprehension iterating over a instead (less efficient):

[ e for i, e in enumerate(a) if i in b ]

#=> ['the dog', 'the frog went', 'empty']

O with lambda:

map( lambda x: a[x], b )

Upvotes: 0

Alessandro Cosentino
Alessandro Cosentino

Reputation: 2364

Yet another solution: if you are willing to use numpy (import numpy as np), you could use its fancy indexing feature (à la Matlab), that is, in one line:

c = list(np.array(a)[b])

Upvotes: 0

florex
florex

Reputation: 963

An other way is :

map(a.__getitem__, b)

Upvotes: 2

Ale Sanchez
Ale Sanchez

Reputation: 566

Using list comprehension, just do:

c = [a[x] for x in b]

Upvotes: 5

Related Questions