Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract elements from a list using indices in Python? [duplicate]

Tags:

python

list

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]).

like image 386
Stefano Borini Avatar asked Apr 12 '10 11:04

Stefano Borini


People also ask

How do I find the index of a duplicate element in a list?

Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.


2 Answers

Perhaps use this:

[a[i] for i in (1,2,5)] # [11, 12, 15] 
like image 196
unutbu Avatar answered Sep 16 '22 14:09

unutbu


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]     
like image 39
lugte098 Avatar answered Sep 16 '22 14:09

lugte098