2

I have a list that like:

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

I want to slice, selecting 'a', 'c', 'd'. I try doing:

list[0, 2, 3]

and I receive an error message that says: 'list indices must be integers or slices, not tuple'.

I also tried:

list[True, False, True, True, False]

and I receive an error message that says: 'list indices must be integers or slices, not list'.

Can anyone help me?

Regards

alelew
  • 103
  • 1
  • 7

4 Answers4

2

You can use list comprehension:

result = [list[q] for q in selection]

where selection is the list with the indices you want to extract.

As a general rule: do not used list as variable name as it overrides the builtin list()

Christian K.
  • 2,677
  • 15
  • 37
1
slicedList = [list[0],list[2],list[3]]
Smolakian
  • 334
  • 1
  • 13
1

try this:

li1 = ['a', 'b', 'c', 'd', 'e']
selected = ['a', 'c', 'd']
list(filter(lambda x:x in selected, li1))
theabc50111
  • 156
  • 11
0

You can use operator.itemgetter:

from operator import itemgetter

i = itemgetter(0, 2, 3)
lst = ["a", "b", "c", "d", "e"]

print(i(lst))

Prints:

('a', 'c', 'd')
Andrej Kesely
  • 118,151
  • 13
  • 38
  • 75