[Tutor] Mixing generator expressions with list definitions

Ed Singleton singletoned at gmail.com
Wed Apr 18 14:43:03 CEST 2007


On 4/18/07, Kent Johnson <kent37 at tds.net> wrote:
> Ed Singleton wrote:
> > I would like to be able to do something along the lines of:
> >
> >>>> my_list = [1, 2, x for x in range(3,6), 6]
> >
> > However this doesn't work.  Is there any way of achieving this kind of thing?
>
> my_list = [1, 2] + range(3,6) + [6]

I thought I'd got past the point where there were stupidly simple
answers to my questions ;)  Oh well.  Thanks yet again, Kent.

> or, to build it in steps,
> my_list = [1, 2]
> my_list.extent(range(3, 6))
> my_list.append(6)

Yeah, that's how I had ben doing it.  I don't really like it for some
reason, though I'm not clear why I don't like it.  I think maybe
because it's quite verbose so it's a bit difficult for me to read it
afterwards, and makes typos more likely ;)

> By the way I can't think of any reason to write "x for x in range(3, 6)"
> instead of just "range(3, 6)". range() returns a list which can be used
> almost anywhere the generator expression can be. If you need an explicit
> iterator use iter(range(3, 6)).

Sorry, I oversimplfied my example.  I'm actually doing:

widgets = [(organisation_widget,(),{'organisation':organisation})]
widgets.extend([(event_widget,(),{'event':event}) for event in
organisation.events])
widgets.append((event_form,(),{'values':values}))

so that later on I can just iterate through the widgets like so:

for (widget, args, kwargs) in widgets:
    widget.display(*args, **kwargs)

Ed


More information about the Tutor mailing list