alex1997 alex1997 - 1 month ago 6
Python Question

Python, removing elements from lists

Hi i'm a newbie and i have a problem with a function.
I have two lists:

>>> a = ['a0', 'b1', 'a2', 'b3', 'a4', 'b5']
>>> b = ['b0', 'a1', 'b2', 'a3', 'b4', 'b5']


I want to remove elements in common and the bigger one in the same position; my output should be:

>>> function(a,b)
>>> a
['a0', 'a2', 'a4']
>>> b
['a1', 'a3']


I tried this:

>>> def function(a,b):
for i1,i2 in zip(a,b):
if i1 == i2:
a.remove(i1)
b.remove(i2)
elif i1 < i2:
b.remove(i2)
else:
a.remove(i1)


But it returns me:

>>> function(a,b)
>>> a
['a0', 'b1', 'a2', 'b3', 'a4', 'b5']
>>> b
['a1', 'a3', 'b5']


What's my mistake?

Answer

In python 2 that would work but in python 3 zip has become a generator function: it creates the items on demand (more info here about various zip, izip stuff and differences between 2 & 3)

Which means that since you're modifying a and b in the loop it amounts to iterating over changing lists (it's slightly less obivious because of the zip function).

To fix that, zip a copy of your input lists

def function(a,b):
        for i1,i2 in zip(a[:],b[:]):
            if i1 == i2:
                a.remove(i1)
                b.remove(i2)
            elif i1 < i2:
                b.remove(i2)
            else:
                a.remove(i1) 
Comments