Priyan Selva
Priyan Selva

Reputation: 13

Python for loop iterating with same variable names throws error

I am learning Python. I came across the following abnormal result, while using Python 3.6.0 REPL.

a = [1, 2, 3]
for a in a :
   print(a)

output:

1
2
3

Again.

output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

I could see that value of 'a'.

>>>a
3

It works other iterators like i

I don't know how to search for the error in google. Why did a change?

Upvotes: 1

Views: 183

Answers (2)

AntiMatterDynamite
AntiMatterDynamite

Reputation: 1512

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

Upvotes: 2

Idan Str
Idan Str

Reputation: 614

Of course it will throw exception. It is the same name in the same scope.

Upvotes: 0

Related Questions