Skip to content

Instantly share code, notes, and snippets.

@swaroopch
Created July 20, 2010 07:45
Show Gist options
  • Save swaroopch/482653 to your computer and use it in GitHub Desktop.
Save swaroopch/482653 to your computer and use it in GitHub Desktop.
Wondering of a clean way to flatten a list (multiple levels)
#!/usr/bin/env python
def flatten(array):
out = []
def real_flatten(array):
for item in array:
if isinstance(item, (list, tuple, set)):
real_flatten(item)
else:
out.append(item)
real_flatten(array)
return out
if __name__ == '__main__':
abc = [4,5,6,[1,2],[3,[7, 8],9],10]
print flatten(abc)
# Output: [4, 5, 6, 1, 2, 3, 7, 8, 9, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment