Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutating the loop variable during an iteration

Tags:

python

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

like image 692
LondonRob Avatar asked Jan 03 '23 09:01

LondonRob


1 Answers

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)
like image 84
hspandher Avatar answered Jan 15 '23 04:01

hspandher