1

Say

a = [1,2,3,4,5,6,7]

If I want to select the elements 0 to 4 of that I can do so by

a[0:3]

Now what I would like to do is to select, say, the first, third and fourth element with a similar command. So I would like to build the list [2,4,5] by a command such as

a[???]

What would I have to fill in for the ????

(I do not want to do [a[1],a[3],a[4]], since in my case a is the return of the function, and only want to call it once.)

Thanks for suggestions!

Britzel
  • 205
  • 3
  • 8

2 Answers2

1

You could use mapping like the follwoing:

a = [1,2,3,4,5,6,7]

res = list(map(a.__getitem__, [1,3,5]))
print(res)
# [2, 4, 6]

Other option is to use operator.itemgetter:

import operator
b= [1,3,5]
res = operator.itemgetter(*b)(a)
print(list(res)
# [2, 4, 6]
David
  • 8,113
  • 2
  • 17
  • 36
0
x = a[1] + a[3:5]

I think shorter version doesn't exist.