[Tutor] Would somebody kindly...

Alan Gauld alan.gauld at btinternet.com
Fri Oct 31 02:52:42 CET 2014


On 30/10/14 05:39, Clayton Kirkwood wrote:

> So, in this case, the assignment to x is external.
> Often I don't see an external assignment, but there
 > is an item in the first position within the comprehension.

I've been reviewing this thread and there might be a concept
that you are missing. Several of us have spoken about
expressions and that the first "item" in a comprehension
is an expression. Indeed the comprehension as a whole is
an expression.

But do you understand the significance of "an expression"
in Python (or general programming terms) as opposed to
simple English language terms?

If not, much of the significance of what has been
said so far will have been missed.

An expression is basically a piece of code that
returns a value. So

X
X+3
X*Y
4**2
pow(4,2)
round((3*2)/(4+7))
[item for item in values if item > 42]

are all expressions: they return values.

Someone (Steven?) mentioned that the comprehension can
be thought of as a kind of anonymous function that returns
a value and the values inside are effectively hidden from
the outer program. And a function call(like pow() above) are expressions 
too.

The point of expressions is that the resulting value can
be assigned to variables or used in tests or included
in data. Anywhere that a literal value can be used you
can use an expression. Including a list comprehension.

The significant thing about a list comprehension is that
it returns a new list value. It does not modify the collection
inside the comprehension and it does not modify any lists
outside the comprehension. It returns a new list comprising
all the expression values of the first element in the
comprehension that match the optional conditional expression.

result = [result_expression
             for variable in collection
                if filter_expression]

Now, maybe I'm misreading things and you already understood
all of that, in which case I apologize. On the other hand
it might just clear up what we mean when we talk about
expressions.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list