Last active
March 24, 2021 22:08
-
-
Save sadikkuzu/f7a41429a960be8ecb1f7d82a53fb9db to your computer and use it in GitHub Desktop.
Juggle with lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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