Home > front end >  python remove elements from one list based on indices from another list
python remove elements from one list based on indices from another list

Time:11-29

I have 2 lists. First list is a list of values, values, second list is a list of indices, position.

position = [1, 0 ,0 ]
values = [2, 6, 1]

output: [6, 2, 1]

what i want to do is, iterate the position list and remove the corresponding element at that position in the values list.

  • So, in first pass, it will remove values[position[0]], that is 6, then the resultant values array will also change to [2, 1].
  • In the second pass, it will remove values[position[1]], that is 2, and the resultant values array will become [1].
  • Lastly it will remove 1.

This is my code in O(n**2). Any optimization is appreciated. Thanks!

position = [1, 0 ,0 ]
values = [2, 6, 1]
for i in range(len(position)):
    while len(values) > 0:
        x = values[position[i]]
        print(x)
        values.remove(x)
        break

CodePudding user response:

First note: your while loop is useless, as you break at first iteration. Your loop is strictly equivalent to

for i in range(len(position)):
    x = values[position[i]]
    print(x)
    values.remove(x)

Then : iterate over values and not indices for position, and use list.pop to get and remove at the same time

result = []
for pos in position:
    result.append(values.pop(pos))
print(result)  # [6, 2, 1]

CodePudding user response:

To do that, you can use the .pop() method.

position = [1, 0 ,0 ]
values = [2, 6, 1]

for idx in position:
    values.pop(idx)
  • Related