Flattening list in python
Question: I have seen many posts regarding how to flatten a list in Python. But I was
never able to understand how this is working: `reduce(lambda x,y:x+y,*myList)`

Could someone please explain, how this is working:

    
    
    >>> myList = [[[1,2,3],[4,5],[6,7,8,9]]]
    >>> reduce(lambda x,y:x+y,*myList)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>>
    

Linked already posted :

[How to print list of list into one single list in python without using any
for or while loop?](http://stackoverflow.com/questions/20402558/how-to-print-
list-of-list-into-one-single-list-in-python-without-using-any-for-o)

[Flattening a shallow list in
Python](http://stackoverflow.com/questions/406121/flattening-a-shallow-list-
in-python)

[Flatten (an irregular) list of lists in
Python](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-
of-lists-in-python)

If anybody thinks this is duplicate to other post, I'll remove it once I
understood how it works.

Thanks.


Answer: It is equivalent to :

    
    
    def my_reduce(func, seq, default=None):
        it = iter(seq)
        # assign either the first item from the iterable to x or the default value
        # passed to my_reduce 
        x = next(it) if default is None else default
        #For each item in iterable, update x by appying the function on x and y
        for y in it:
            x  = func(x, y)
        return x
    ... 
    >>> my_reduce(lambda a, b: a+b, *myList, default=[])
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> my_reduce(lambda a, b: a+b, *myList)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> from operator import add
    >>> my_reduce(add, *myList)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> my_reduce(lambda a, b: a+b, ['a', 'b', 'c', 'd'])
    'abcd'
    

Docstring of `reduce` has a very good explanation:

    
    
    reduce(...)
        reduce(function, sequence[, initial]) -> value
    
        Apply a function of two arguments cumulatively to the items of a sequence,
        from left to right, so as to reduce the sequence to a single value.
        For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
        ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
        of the sequence in the calculation, and serves as a default when the
        sequence is empty.
    

