List Info

Thread: Mixing generator expressions with list definitions




Mixing generator expressions with list definitions
user name
2007-04-18 06:55:35
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
_______________________________________________
Tutor maillist  -  Tutorpython.org
http://
mail.python.org/mailman/listinfo/tutor

Re: Mixing generator expressions with list definitions
country flaguser name
United States
2007-04-18 07:17:34
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  -  Tutorpython.org
> http://
mail.python.org/mailman/listinfo/tutor
> 

_______________________________________________
Tutor maillist  -  Tutorpython.org
http://
mail.python.org/mailman/listinfo/tutor

Re: Mixing generator expressions with list definitions
country flaguser name
United States
2007-04-18 07:18:45
Kent Johnson wrote:

> my_list.extent(range(3, 6))

should be
   my_list.extend(range(3, 6))

Kent
_______________________________________________
Tutor maillist  -  Tutorpython.org
http://
mail.python.org/mailman/listinfo/tutor

[1-3]

about | contact  Other archives ( Real Estate discussion Medical topics )