tags:

views:

126

answers:

4

I feel suddenly uneasy of not being able to perform this operation easily. It could be that I'm tired, or that there's really no way (google didn't help), but...

if you have a list in python, and want to extract element at indices say 1, 2 and 5 into a new list, how do you do ?

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]

any better way ?

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

+9  A: 

Perhaps use this:

[a[i] for i in (1,2,5)]
# [11, 12, 15]
unutbu
btw this is also much faster. fetching K items from a list of size N is of complexity O(K) here and O(N*K) in OP's solution.
yairchu
ok... thank you. This was damn trivial, and it's clear that I'm too tired.
Stefano Borini
No problem. Any day I can answer a Stefano Borini question is a (rare, but) good day :)
unutbu
uh ? ..........
Stefano Borini
Personally I've never seen Python written that way, but I have to agree. That is pretty genius, and readable!
Xavier Ho
+2  A: 

Try

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

result = [numbers[i] for i in indices]
bebraw
+1  A: 

Bounds checked:

 [a[index] for index in (1,2,5,20) if 0 <= index < len(a)]
 # [11, 12, 15] 
Charles Beattie
+1  A: 

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