[Tutor] build list of non-empty variables

John Fouhy john at fouhy.net
Thu Jul 10 04:32:13 CEST 2008


On 10/07/2008, Kent Johnson <kent37 at tds.net> wrote:
> On Wed, Jul 9, 2008 at 9:38 PM, John Fouhy <john at fouhy.net> wrote:
> > Is the generator expression grammar right?  How do I parse, e.g.,
>  > '(x+1 for x in range(10))'?  Seems like there's nothing there for
>  > 'range(10)'.  Like it should replace 'or_test' with 'old_expression'.
> I can't figure out how to parse that either, as a gen exp or a list comp.

Oh, wait, I got it.  I just didn't follow the chain far enough.

old_expression -> or_test -> and_test -> not_test -> comparison ->
or_expr -> xor_expr -> and_expr -> shift_expr -> a_expr -> m_expr ->
u_expr -> power -> primary -> call (or replace call with atom)

So the other difference between list comprehensions and generator
expressions is that list comprehensions get to use "old_expression"s
whereas generator expressions start with "or_test"s.  An
old_expression can be an old_lambda_form, which means that this is
valid syntax:

>>> [x for x in lambda y: y**2]

whereas this is not:

>>> (x for x in lambda y: y**2)

I'm lost for how to come up with a use for that, though (or even a way
to write code like that without producing a TypeError: 'function'
object is not iterable).

-- 
John.


More information about the Tutor mailing list