list comprehension question

Raymond Hettinger python at rcn.com
Mon Mar 25 02:37:59 EST 2002


"Tripp Scott" <tripps81 at yahoo.com> wrote in message
news:mailman.1017031538.14132.python-list at python.org...
> At 25/03/2002 07:37, brueckd at tbye.com wrote:
> thanks for the tip. actually, the essence of what i wanted to
> ask was: "can that SOMETHING be a list of more than one elements
> which will be _flatly_ added to the result list." as another
> example, can i generate this list
>
>   [1,1  2,2,2,  3,3,3,3, 4,4]

I don't see the pattern.  I presume you mean:
[1,1,  2,2,2,  3,3,3,3, 4,4,4,4,4 ]

>
> with a list comprehension that contains one 'for' clause?

I think you are asking for a general purpose solution to the
problem of using list comprehensions in an 'extend' rather
than 'append' mode.

The general purpose technique is to build it unflattened and
then wrap it with 'reduce' to flatten it.

Applying that general technique to your specific example is easy:

>>> import operator
>>> reduce(operator.add, [[i]*(i+1) for i in range(1,5)])
[1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4]

Hope this helps you train your pet Python,


Raymond Hettinger





More information about the Python-list mailing list