Hide
Siafoo – the intersection of pastebin, help desk, version control, and social networking Join Siafoo Now or Learn More

Flatten list / tuple Atom Feed 0

In Brief Apparently Python doesn't have a builtin flatten method... (yes you have the right to be annoyed!). Here's a simple recursive method to do the job. It will turn this ((1, 2), (3, 4), (5, 6)) into (1, 2, 3, 4, 5, 6)... more
# 's
 1def flatten(lst):
2
3 res = []
4
5 for l in lst:
6 if isinstance(l, list) or isinstance(l, tuple):
7 res.extend(flatten(l))
8 else:
9 res.append(l)
10
11 return res

Apparently Python doesn't have a builtin flatten method... (yes you have the right to be annoyed!). Here's a simple recursive method to do the job. It will turn this ((1, 2), (3, 4), (5, 6)) into (1, 2, 3, 4, 5, 6)

This method won't be able to handle deeply nested lists well but it works well for lists of coordinate tuples ((x,y,z)... )