[Tutor] Mixing generator expressions with list definitions

Ed Singleton singletoned at gmail.com
Wed Apr 18 13:55:35 CEST 2007


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?

I tried:

>>> my_list = [1, 2, *(x for x in range(3,6)), 6]

which also doesn't work.

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]
...
>>> 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


More information about the Tutor mailing list