# reduce to be removed?

Dustan DustanGroups at gmail.com
Sun Nov 12 03:25:36 CET 2006

```Fredrik Lundh wrote:
> Dustan wrote:
>
> >>>> foo =\
> > [[[1,2,3],[4,5,6],[7,8,9]],
> >  [[3,2,1],[6,5,4],[9,8,7]]]
> >
> > Here, foo appears to be a 3-dimensional list - except it's supposed to
> > be 2-dimensional. The inner-list-of-lists is a result of how I'm
> > producing the data, and now I want to do a mass-concatenation (or
> > extending) of the inner-list-of-lists, and come up with this result:
> >
> >>>> foo == [[1,2,3,4,5,6,7,8,9],[3,2,1,6,5,4,9,8,7]]
> > True
>
> that still doesn't explain your "the expression must be used in a list
> comprehension" requirement, though.

Oh, right; sorry about the confusion. The list isn't quite that simple,
and in order to pull the right pieces together, I use a list
comprehension.

> assuming that the sizes are
> varying, and at least sometimes a lot larger than 3x3, I'd probably
> write the above as
>
>      for index, item in enumerate(foo):
>          this = []
>          for i in item:
>              this.extend(i)
>          foo[index] = this

I'll see if that works.

> which should be pretty efficient, since it avoids unnecessary function
> calls, and is amortized linear time instead of O(N**2).
>
> or, if I was in a hurry, and didn't really care if the inner sequences
> were lists or tuples:
>
> 	foo = map(Tkinter._flatten, foo)
>
> </F>

Steven D'Aprano wrote:
> I don't know if this is the best, but it didn't take long to come up with
> it:
>
> >>> foo = [[[1,2,3],[4,5,6],[7,8,9]],
> ... [[3,2,1],[6,5,4],[9,8,7]]]
> >>>
> >>> def unroll(list3d):
> ...     newl = []
> ...     for sublist in list3d:
> ...             newl.append(sum(sublist, []))
> ...     return newl

deja vu...

> >>> bar = unroll(foo)
> >>> bar
> [[1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 2, 1, 6, 5, 4, 9, 8, 7]]
>
>
> Repeat after me:
>
> "Not everything has to be a one-liner."

Not everything has to be a one-liner. But readability helps.

> If sum() is too slow, because your sub-lists are huge, you can easily
> factor that out and replace it with something using extend.
>
>
> --
> Steven.

```