How to flatten a list to return a new list with all the elements?

Solution 1:

Generally, this would be done recursively, for example:

def flatten(input_, output=None):
    if output is None:
        output = []
    if isinstance(input_, basestring):
        output.append(input_)
    else:
        for item in input_:
            try:
                flatten(item, output)
            except TypeError:
                output.append(item)
    return output

This will work with any combination of iterable containers (e.g. set, list, tuple, dict (keys only)) and contents (e.g. int, float, str), using the common EAFP Python style. Note the specific exception for strings, which you probably don't want to be unpacked!

A few examples of usage:

>>> flatten([1, [2, [3, [4, 5], 6], 7], 8])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> flatten([1, "foo", ["bar", 2], 3])
[1, 'foo', 'bar', 2, 3]
>>> flatten([1, (2, 3), {4: 5}])
[1, 2, 3, 4]
>>> flatten("hello")
['hello']

And what happens with non-iterables as direct arguments:

>>> flatten(1)

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    flatten(1)
  File "<pyshell#1>", line 4, in flatten
    for item in input_:
TypeError: 'int' object is not iterable