Skip to content

Instantly share code, notes, and snippets.

@sadikkuzu
Last active March 24, 2021 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sadikkuzu/f7a41429a960be8ecb1f7d82a53fb9db to your computer and use it in GitHub Desktop.
Save sadikkuzu/f7a41429a960be8ecb1f7d82a53fb9db to your computer and use it in GitHub Desktop.
Juggle with lists
def flatten(list_of_lists):
if len(list_of_lists) == 0:
return list_of_lists
if isinstance(list_of_lists[0], list):
return flatten(list_of_lists[0]) + flatten(list_of_lists[1:])
return list_of_lists[:1] + flatten(list_of_lists[1:])
print(flatten([[1, 2, 3, 4], [5, 6, 7], [8, 9], [[10]]]))
# output
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(flatten([[1,'a',['cat'],2],[[[3]],'dog'],4,5]))
# output
# [1, 'a', 'cat', 2, 3, 'dog', 4, 5]
import itertools
# initializing the data
data = [[1, 2, 3], [4, 5], [6, 7, 8, 9, 10]]
# flattening the list and storing the result
flat_list = itertools.chain(*data)
# converting iterable to list and printing
print(list(flat_list))
# output
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def mirrored(listtree):
return [(mirrored(x) if isinstance(x, list) else x)
for x in reversed(listtree)]
print(mirrored([[1, 2], [3, 4], [5, 6, 7]]))
# output
# [[7, 6, 5], [4, 3], [2, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment