0

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?

Patrick Haugh
  • 55,247
  • 13
  • 83
  • 91
cjg123
  • 443
  • 5
  • 20
  • 1
    Possible duplicate of [How to access List elements](https://stackoverflow.com/questions/10613131/how-to-access-list-elements) – d_kennetz Dec 07 '18 at 18:44
  • 1
    @d_kennetz not at all a duplicate of that, even though I agree that from the title it could look like so. – Alessandro Cosentino Dec 07 '18 at 18:55
  • @AlessandroCosentino the premise is the same. accessing items in a list by their index (just because indexes are in another list) doesn't really change much. – d_kennetz Dec 07 '18 at 19:54

4 Answers4

6

Using list comprehension, just do:

c = [a[x] for x in b]
Ale Sanchez
  • 510
  • 7
  • 16
2

An other way is :

map(a.__getitem__, b)
florex
  • 818
  • 7
  • 9
0

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])
Alessandro Cosentino
  • 2,050
  • 1
  • 18
  • 28
0

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 )
iGian
  • 10,602
  • 3
  • 18
  • 34