I am looping through a list of tuples and, each iteration, I am appending some extra elements to the current loop variable, then performing an action with the new list.
The temptation is to modify the loop variable to include the extra elements, then do something with it.
Consider the following code snippet:
required_part = (0, 4)
optional_part = [(1, 2), (1, 3), (2,3)]
for x in optional_part:
x += required_part
x = sorted(x)
print(x)
But something about mutating the loop variable during a loop makes me feel uneasy.
Are there any situations when mutating the loop variable will produce unexpected results or can I just stop worrying?
Note: there seems to be plenty of discussion about mutating the iterable. This question is rather about mutating the loop variable
As long as you're not changing the collection itself, it doesn't matter. The problem only arises when you try to add/delete from the very collection, you're iterating over.
# Say something like this
for x in optional_part:
optional_part.remove(x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With