Search code examples
pythonpython-3.xnested

why my for loop is skipping elements in list even if not manipulating the iterating list?


lst1=[['harry', 44.0], ['jack', 44.0], ['bunny', 6.0]]
m=['harry', 44.0]  #want to remove elements having 44.0 
arr2=lst1
print("Before",lst1)
for i in lst1:
    print("i=",i)  #Not printing all elements
    if i[1]==m[1]:
        arr2.remove(i)

Here "before" and "i" are not same and why?


Solution

  • arr2=lst1 doesn't make a copy, it just creates a reference to (the same) list lst1.

    Thus, by changing arr2 in arr2.remove(i), you're also altering lst1.

    Use arr2 = lst1[:] (or arr2 = lst1.copy), but people tend to use the first version) to make a copy instead, that you can freely alter without harming lst1.

    This mutability issue applies to both lists and dicts, but not to strings, tuples and "simple" variables such as ints, floats or bools.