0

So I just noticed this doesn't work because POP is removing elements from both lists.

l1 = [1,2,3,4]
l2 = l1

l2.pop(1)
print(l1)

>> [1, 3, 4]

How this could be solved? I would like to iterate over l1 removing n elements from l2.

for i in range(0, len(l1), 2):
    l2.pop(i)

But I got out of index because both list one and two were modified

  • 2
    *It's the same list*. See: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Apr 02 '20 at 18:37
  • 1
    `l2 = l1[:]` to make a copy otherwise as @juanpa.arrivillaga mentioned you are pointing at the same list – gold_cy Apr 02 '20 at 18:38
  • I see, thank guys! – Georgia Fernández Apr 02 '20 at 18:39
  • 1
    Note, this isn't going to fix your problem. You aren't iterating over `l1`, you are iterating over a `range` object. The problem is that the indices in `l2` won't match up when you change it's size. Also, this algorithm is highly inefficient, being quadratic time. A more efficient approach is to not involve `.pop` and just do `l2 = l[::2]`, or if you feel like doing with a loop, *grow* `l2` using `.append` as you iterate over `l1` Removing from inside a list is inefficient, appending to the end is very efficient – juanpa.arrivillaga Apr 02 '20 at 18:40
  • 1
    That was really, really, useful. Thanksss! :) @juanpa.arrivillaga – Georgia Fernández Apr 02 '20 at 22:21

0 Answers0