List Comprehension Syntax

James Moughan moughanj at tcd.ie
Sun Jul 11 12:40:29 EDT 2004


Andrea Griffini <agriff at tin.it> wrote in message news:<f5h0f0d4l7a9qhj0kqtn8l1cvmanh7ge1b at 4ax.com>...
> On 10 Jul 2004 16:41:16 +0300, Ville Vainio <ville at spammers.com>
> wrote:
> 
> >I think you'll find that you don't need to sacrifice any of your old
> >models or even aesthetic preferences to appreciate LCs. 
> 
> I'm quite new to python, and I found LC quite simple to understand
> and powerful. The only "suprising" part for me was that the looping
> variable is not local... I slipped on that a couple of times.
> A list comphrension is very "local" in my mind ... I would say that
> [x*x for x in xrange(10)] is just a list of perfect squares, but
> instead it's not... it's that AND the assignment to x of the value 9.
> 
> Andrea

Yup, scoping rules are usually the one confusing part of Python. I was
especially surprised by the result of:

l = [lambda y: x*y for x in range(10)]

which doesn't do remotely what you'd expect.  Especially if you
learned about list comprehensions in Haskell, with no variable
assignments... :-)



More information about the Python-list mailing list