[Tutor] reduce with comprehension

John Fouhy john at fouhy.net
Mon Nov 21 23:26:03 CET 2005


On 21/11/05, János Juhász <janos.juhasz at velux.com> wrote:
> I can't imagine how this could be made with list comprehension.
>
> >>> import operator
> >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
> >>> reduce(operator.add, a) # it makes a long list now
> ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9])

Everything is possible with list comprehensions!

>>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9]))
>>> [x for y in a for x in y]
[[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]]

We can even go a level deeper!

>>> [x for z in a for y in z for x in y]
[1, 2, 3, 31, 32, 4, 5, 6, 7, 71, 72, 8, 9]

Just make sure your depth is consistent throughout.

And remember that that single-line expression is hiding nested FOR loops!

--
John.


More information about the Tutor mailing list