By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,676 Members | 2,262 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,676 IT Pros & Developers. It's quick & easy.

variable scope in list comprehensions

P: n/a

there is something I don't understand about list comprehensions.

I understand how does this work:
print [[y for x in range(8)] for y in range(8)]

However I don't understand why this one works:
print [[y for y in range(8)] for y in range(8)]

In this second example I have one loop nested in another. Both loops uses
the same variable - y. How is it that those loops do not conflict with each

For a moment I thought that maybe list comprehension has its own scope, but
it doesn't seem to be so:
print [[y for y in range(8)] for y in range(8)]
print y

Does anybody understand it?
Apr 3 '08 #1
Share this Question
Share on Google+
1 Reply

P: n/a
Duncan Booth wrote:
For the OP, in some languages (e.g. C) 'for' loops typically calculate
the value of the loop control variable based on some expression
involving the previous value. Python isn't like that. In Python the data
used to compute the next value is stored internally: you cannot access
it directly.
Great! Now everything is clear.


Apr 5 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.