37

If you have a list in python, and want to extract elements at indices 1, 2 and 5 into a new list, how would you do this?

This is how I did it, but I'm not very satisfied:

>>> a
[10, 11, 12, 13, 14, 15]
>>> [x[1] for x in enumerate(a) if x[0] in [1,2,5]]
[11, 12, 15]

Is there a better way?

More in general, given a tuple of indices, how would you use this tuple to extract the corresponding elements from a list, even with duplication (e.g. tuple (1,1,2,1,5) produces [11,11,12,11,15]).

jpp
  • 159,742
  • 34
  • 281
  • 339
Stefano Borini
  • 138,652
  • 96
  • 297
  • 431

5 Answers5

89

Perhaps use this:

[a[i] for i in (1,2,5)]
# [11, 12, 15]
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
10

I think you're looking for this:

elements = [10, 11, 12, 13, 14, 15]
indices = (1,1,2,1,5)

result_list = [elements[i] for i in indices]    
lugte098
  • 2,271
  • 5
  • 21
  • 30
6

Try

numbers = range(10, 16)
indices = (1, 1, 2, 1, 5)

result = [numbers[i] for i in indices]
Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
5

Use Numpy direct array indexing, as in MATLAB, Julia, ...

a = [10, 11, 12, 13, 14, 15];
s = [1, 2, 5] ;

import numpy as np
list(np.array(a)[s])
# [11, 12, 15]

Better yet, just stay with Numpy arrays

a = np.array([10, 11, 12, 13, 14, 15])
a[s]
#array([11, 12, 15])
Dmitri
  • 757
  • 1
  • 7
  • 15
3

Bounds checked:

 [a[index] for index in (1,2,5,20) if 0 <= index < len(a)]
 # [11, 12, 15] 
Charles Beattie
  • 5,739
  • 1
  • 29
  • 32