tags:

views:

73

answers:

3

Possible Duplicate:
join list of lists in python

Is there in Python a built-in or a particular syntax to accomplish the following on the fly?

def merge(listOfLists):
    result = []
    for l in listOfLists:
        result.extend(l)
    return result

print merge( [[1,2,3,4], [5,6], [7,8,9]] )
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

Excuse me for lameness, but I really don't remember...

+1  A: 

The best solutions are here http://stackoverflow.com/questions/716477/join-list-of-lists-in-python

gnucom
Ok, thanks. I'll close the question.
Federico Ramponi
Just more links to get to the right answer! :-D
gnucom
+3  A: 
>>> alist = [[1,2,3,4], [5,6], [7,8,9]]
>>> merged = [x for sublist in alist for x in sublist]
>>> merged
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
John Machin
A: 

Here's what I use:

def flatten(input):
    """
    Flatten a nested list/tuple structure and return a simple list

    Given [(a,b),c], return [a,b,c]
    """
    ret = []
    if not isinstance(input, (list, tuple)):
        return [input]
    for i in input:
        if isinstance(i, (list, tuple)):
            ret.extend(flatten(i))
        else:
            ret.append(i)
    return ret
Daenyth