[Tutor] Mixing generator expressions with list definitions
Kent Johnson
kent37 at tds.net
Wed Apr 18 14:17:34 CEST 2007
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]
or, to build it in steps,
my_list = [1, 2]
my_list.extent(range(3, 6))
my_list.append(6)
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)).
> I wrote a quick function that allows me to use the generator
> expression as long as it is the last argument:
>
>>>> def listify(*args):
> ... return [arg for arg in args]
or
return list(args)
Kent
> ...
>>>> my_list = listify(1,2, *(x for x in range(3,6)))
>
> but obviously this limits me to using it only at the end of a list.
>
> Any clues on this greatly appreciated.
>
> Thanks
>
> Ed
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list