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
  • 173
  • 3
  • 13

4 Answers4

2
slicedList = [list[0],list[2],list[3]]
Smolakian
  • 414
  • 3
  • 15
1

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,785
  • 18
  • 40
1

try this:

li1 = ['a', 'b', 'c', 'd', 'e']
selected = ['a', 'c', 'd']
list(filter(lambda x:x in selected, li1))
theabc50111
  • 421
  • 7
  • 16
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
  • 168,389
  • 15
  • 48
  • 91