1

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
  • 59,226
  • 13
  • 88
  • 96
cjg123
  • 473
  • 7
  • 23
  • 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

5

Using list comprehension, just do:

c = [a[x] for x in b]
Ale Sanchez
  • 536
  • 1
  • 6
  • 17
2

An other way is :

map(a.__getitem__, b)
florex
  • 943
  • 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,268
  • 1
  • 21
  • 30
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
  • 11,023
  • 3
  • 21
  • 36