Boaz
Boaz

Reputation: 5084

getting elements in a list according to list of indices in python

I have a list of indices, something like:

b=[0,2]  

and a list of elements:

a = ['elem0','elem1','elem2'] 

I need a list that is composed of the elements in a with the indices in b
(in this example: ['elem0','elem2'])

Upvotes: 2

Views: 257

Answers (4)

Marcelo Cantos
Marcelo Cantos

Reputation: 185842

Use a list comprehension:

[a[i] for i in b]

Upvotes: 8

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

Or:

from operator import itemgetter

b=[0,2]
a = ['elem0','elem1','elem2']

print itemgetter(*b)(a)
>>> ('elem0','elem2')

Upvotes: 1

Jürgen Strobel
Jürgen Strobel

Reputation: 2248

>ipython
In [1]: b=[0,2]
In [2]: a = ['elem0','elem1','elem2']
In [3]: [a[i] for i in b]
Out[3]: ['elem0', 'elem2']

Look up "list comprehensions" in the python manual if you don't know them.

Upvotes: 0

Platinum Azure
Platinum Azure

Reputation: 46183

Use a list comprehension to map the indexes to the list:

b=[0,2]
a = ['elem0','elem1','elem2'] 

sublist = [a[i] for i in b]

Upvotes: 0

Related Questions