1

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I thought local variables inside 'for' loop won't be accessible outside the loop. In other words, once loop is executed, its variables will be destroyed. When I used the same names for both the variables, I thought they are within different namesapces and it wont conflict. So, by this assumption, I expected a to retain the same value i.e., list.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.