how to extract elements from a list in python ?
Posted
by Stefano Borini
on Stack Overflow
See other posts from Stack Overflow
or by Stefano Borini
Published on 2010-04-12T11:35:22Z
Indexed on
2010/04/12
11:43 UTC
Read the original article
Hit count: 413
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] )
© Stack Overflow or respective owner