dyao
dyao

Reputation: 1011

Finding Nth element in a list using For Loop

So imagine I want to find the 2nd, 3rd, and 4th element in another list.

position = [2,3,4]

Sample_List = ['a','b','c','d','e']

The loop would give back the result:

['c','d','e']

Upvotes: 2

Views: 1379

Answers (3)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52103

Another approach using operator.itemgetter:

>>> from operator import itemgetter

>>> position = [2,3,4]
>>> Sample_List = ['a','b','c','d','e']
>>> itemgetter(*position)(Sample_List)
('c','d','e')

Upvotes: 1

Pynchia
Pynchia

Reputation: 11590

You can also use

elements = map(lambda k:Sample_List[k], position)

On python3 you need to convert it to a list

elements = list(map(lambda k:Sample_List[k], position))

Upvotes: 1

Simple:

the_elements = [Sample_List[i] for i in position]

Upvotes: 5

Related Questions