Home > Software design >  Is there a way to return a list of numbers contained in a list from another list?
Is there a way to return a list of numbers contained in a list from another list?

Time:09-09

Say I've got:

ranged_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

and another list:

indices_list = [0, 5, 8]

Is there someway I can return items in position 0, 5, 8 from ranged_list so that I get

new_list = [1, 6, 9]

CodePudding user response:

You could use a list comprehension to index the first list using the indices from the second

>>> [ranged_list[i] for i in indices_list]
[1, 6, 9]

CodePudding user response:

You could do:

new_list = [ranged_list[i] for i in indices_list]
  • Related