Search code examples
pythonlistenumerate

Python Replace elements in a list that are also in another list, and delete others


I would like to make a replacement on elements of the list l1 that are also in l2, and delete elements that are not in l2. I don't understand why the following solution does not work: it returns

[33, 33, 'd']

instead of:

[33, 33, '33'] 

Here is my solution:

l1=['a','b','c', 'd']
l2= ['a','b','d','f']
for (i,wor) in enumerate(l1):
    if wor in l2:
        l1[i]= 33
    else:
        del l1[i]

Solution

  • Add some print calls to see what happens:

    l1=['a','b','c', 'd']
    l2= ['a','b','d','f']
    for (i,wor) in enumerate(l1):
        if wor in l2:
            l1[i]= 33
        else:
            del l1[i]
        print(i, len(l1)) 
    

    prints:

    0 4
    1 4
    2 3
    

    The index keeps going according to the original l1 but you changed the size of l1during iteration. This messes everything up. You should not do this.