Flatten a list/tuple and Call a function with tuples

Aneesh Goel NuclearOnslaught at gmail.com
Wed Jul 25 20:25:18 CEST 2007


On Jul 25, 10:33 am, Jeff <jeffo... at gmail.com> wrote:
> def flatten(obj):
>     if type(obj) not in (list, tuple, str):
>         raise TypeError("String, list, or tuple expected in
> flatten().")
>     if len(obj) == 1:
>         if type(obj[0]) in (tuple, list):
>             return flatten(obj[0])
>         else:
>             return [obj[0]]
>     else:
>         return [obj[0]] + flatten(obj[1:])

This seems to work fine only if the last object is the only one with
the tuple or list.  For example:
>>> y = [(1,2),3,4]
>>> y
[(1, 2), 3, 4]
>>> print flatten(y)
[(1, 2), 3, 4]

if the last line is changed to

return flatten([obj[0]]) + flatten(obj[1:])

then it will unpack tuples/lists anywhere in the main collection being
flattened:
>>> y
[(1, 2), 3, 4]
>>> flatten(y)
[1, 2, 3, 4]
>>> z = [1,(2,3),4]
>>> flatten(z)
[1, 2, 3, 4]
>>> x
[1, 2, (3, 4)]
>>> flatten(x)
[1, 2, 3, 4]
>>> k = [(1,2),(3,4)]
>>> flatten(k)
[1, 2, 3, 4]




More information about the Python-list mailing list