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

Time:08-11

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?

CodePudding user response:

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.

CodePudding user response:

So you iterate through the first time with 3 objects in the array and you're printing '1'. During that first iteration right after you print '1' you remove '1'. At the start of your second iteration the list now only has 2 objects. i is now '2'. You print '2' which is now the last item (bunny). The first item is now "jack", but you already printed the first item. That is why you never see "jack".

  • Related