3

I have a list in python that I want to get the a set of indexes out of and save as a subset of the original list:

templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]

and I want this:

   sublist=[[1,    4,    7,                      16,      19,20]]

as an example.

I have no way of knowing ahead of time what the contents of the list elements will be . All I have is the indices that will always be the same.

Is there a single line way of doing this?

testname123
  • 1,061
  • 3
  • 20
  • 43

5 Answers5

6

Using operator.itemgetter:

>>> templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]
>>> import operator
>>> f = operator.itemgetter(0,3,6,15,18,19)
>>> sublist = [list(f(templist[0]))]
>>> sublist
[[1, 4, 7, 16, 19, 20]]
falsetru
  • 357,413
  • 63
  • 732
  • 636
4

Assuming you know what the indices to be selected are, it would work something like this:

indices = [1, 4, 7, 16, 19, 20]
templist = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]]
sublist = []

for i in indices:
    sublist.append(templist[0][i])

This can also be expressed in the form of a list comprehension -

sublist = [templist[0][i] for i in indices]
Chaitanya Nettem
  • 1,209
  • 2
  • 23
  • 45
2

you can use list comprehension with enumerate:

indices = [1,2,3]
sublist = [element for i, element in enumerate(templist) if i in indices]
ToonAlfrink
  • 2,501
  • 2
  • 19
  • 19
2
 mylist = ['A','B','C','D','E','F']
 idx = [0,1,3]
 [mylist[i] for i in idx]

['A', 'B', 'D']

Farid Khafizov
  • 1,062
  • 12
  • 8
1

You can use list comprehension:

indices = set([1,2,3])
sublist = [el for i, el in enumerate(orig_list) if i in indices]

Or you can store indices in a list of True/False and use itertools.compress:

indices = [True, False, True]
sublist = itertools.compress(orig_list, indices)
Alex Shkop
  • 1,992
  • 12
  • 12