2
votes

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?

5
how are the indices stored? - Chaitanya Nettem
What do you mean? Python give each element in a list it's own index? - testname123
so tell me if i understood this correctly: you have a list, you have some indices and you want to extract a sub list which contains elements of the list at those indices. - Chaitanya Nettem
yes sir. They are scattered all over the index, so I'm suspicious that the : operator won't work since that does consecutive element selection - testname123
so how do you know which indices in the list to select? - Chaitanya Nettem

5 Answers

4
votes

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]
5
votes

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]]
1
votes

you can use list comprehension with enumerate:

indices = [1,2,3]
sublist = [element for i, element in enumerate(templist) if i in indices]
1
votes

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)
1
votes
 mylist = ['A','B','C','D','E','F']
 idx = [0,1,3]
 [mylist[i] for i in idx]

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