2

Is it expected that nested variables in Python overlaps? for example:

for i in range(1,10):
    x = [0xFF for i in range(6)]
    print(i)

what is the expected result (sequence) ? With Python 2.7 I'm getting nine fives.

4 Answers 4

4

What you see is a side-effect of using list comprehensions. The iterator variable inside the list comprehension is identical with the one of the for loop. This means that the iterator variable of the list comprehension is not local the expressions itself.

Example:

>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print x
9

So both iterator variable names should be distinct.

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

Comments

3

Python does not have block scope. So variables you change inside a block will be visible outside that block. Only classes, functions and modules create scopes.

Comments

1

i will be pointing to the last element in range(6) i.e. 5, when you are printing it

when the list comprehension completes the value of i is 5, which is what you get while printing

your external loop runs for range(1,10) i.e. 9 times

In [47]: len(range(1,10))
Out[47]: 9

Comments

0

When you declare any variable it will be store the value. In python when you initialise any variable and store some value it will be available till the variable will not destroy. So when you write x = 10 inside the loop you will get the x out side the loop also. If you want to delete that variable then type del x then you will not get the value of the x

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.