Joe Iddon
Joe Iddon

Reputation: 20424

Pythonic way to creating a list of certain elements

Taking a list, l, I would like to generate a new list of the elements at indexes:

0, 1, 2, 3, 2, 4, 5, 4, 6, 7, 6, 8, 9, 8, 0

I know it seems a bit strange, but it is necessary for a problem.


As for what I have tried, I am currently using the following, but was hoping that someone has something shorter and cleaner than this.

[*l[0:3], l[3], l[2], l[4], l[5], l[4], l[6], l7], l[6], l[8], l[9], l[8], l[0]]

Upvotes: 1

Views: 63

Answers (3)

cdlane
cdlane

Reputation: 41872

Using map with an item getter should do the job:

>>> letters = list('ABCDEFGHIJ')
>>> indexes = [0, 1, 2, 3, 2, 4, 5, 4, 6, 7, 6, 8, 9, 8, 0]
>>> print(list(map(letters.__getitem__, indexes)))
['A', 'B', 'C', 'D', 'C', 'E', 'F', 'E', 'G', 'H', 'G', 'I', 'J', 'I', 'A']
>>> 

Upvotes: 2

honorius
honorius

Reputation: 491

Items used as l values are equal to their index, so that you can verify result easily:

indexes = [0, 1, 2, 3, 2, 4, 5, 4, 6, 7, 6, 8, 9, 8, 0]

l = list(range(15))
print(l)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

result = [l[i] for i in indexes]
print(result)  # [0, 1, 2, 3, 2, 4, 5, 4, 6, 7, 6, 8, 9, 8, 0]

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83527

You can use a list comprehension:

source = [......]
indexes = [.......]
filteredByIndexes = [source[i] for i in indexes]

Upvotes: 2

Related Questions