0
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?

  • Does this answer your question? [Strange result when removing item from a list while iterating over it](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) – Chris Aug 11 '22 at 15:13
  • @Chris I think that's the wrong duplicate. In particular, because the OP explicitly states in the title "even if not manipulating the iterating list", so they are aware of that fact. – 9769953 Aug 11 '22 at 15:14
  • @9769953 They are manipulating the iterating list - even if they don't know they are – Chris Aug 11 '22 at 15:16
  • @Chris Yes, but they are aware they shouldn't manipulate the iterating list. The OP just missed the problem with mutable data structures. Which is likely a different duplicate, but not this one. – 9769953 Aug 11 '22 at 15:17

2 Answers2

1

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.

9769953
  • 10,344
  • 3
  • 26
  • 37
0

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".

  • 1
    This is not the core of the mistake the OP made. – 9769953 Aug 11 '22 at 15:18
  • You're right. It's not the core mistake, but it is essentially what is happening. I would upvote your answer but I don't have 15 points. Sorry. – Samofhearts Aug 11 '22 at 15:22
  • Yes, but that doesn't help the OP. They know what they shouldn't do. You're just explaining that again, but it won't solve the issue for the OP. – 9769953 Aug 11 '22 at 15:23
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 15 '22 at 19:07