Python for loop iterating with same variable names throws error

Solution 1:

In Python when you do

for x in y:
    pass#your code here

x is defined outside the for loop, and you can use it like a normal variable after the loop ended.

If you do something like

for a in range(10):
    pass
print(a)

it will print 9 since that is the last value a had inside the loop.

For the specific case in which both the iterable (the list) and the variable used to iterate over it are named the same, as you can see a changes to each value then stays as the last value as I mentioned.

Then when you run it a second time a is just an integer, not a list, and thus it can't be iterated over.

If you want to know why the loops doesn't break after the first iteration (since a is not the original list after the first iteration) it's because the original list is still in memory until the loop exits. It's just not addressable by its name, after the loop ends it will be completely removed from memory