0

I'm trying to remove some items from a list, and the required indexes are in another list.

I've tried list.pop(), but it also removes items from the parent list, just like list.remove()

sequence = [3, 6, 5, 8, 10, 20, 15]
sortS = sorted(sequence)
seq = sequence
for i in range(len(sequence)):
    seq.remove(sequence[i])
    sortS.remove(sequence[i])


print(sequence)
>>>[]
midnqp
  • 29
  • 1
  • 10
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – mkrieger1 May 05 '19 at 17:55

1 Answers1

1

Use .copy() when you assign 1 list element to other. In Python it simply references to that variable and if any changes is made to that variable will be made to referenced one too.

With using .copy() new memory space will be created and any change to this won't affect the original

sequence = [3, 6, 5, 8, 10, 20, 15]
sortS = sorted(sequence)
seq = sequence.copy()
for i in range(len(sequence)):
    seq.remove(sequence[i])
    sortS.remove(sequence[i])


print(sequence)

output

[3, 6, 5, 8, 10, 20, 15]
palvarez
  • 1,508
  • 2
  • 8
  • 18
sahasrara62
  • 10,069
  • 3
  • 29
  • 44