Skip to content

Instantly share code, notes, and snippets.

@igarag
Last active January 30, 2020 08:30
Show Gist options
  • Save igarag/f57022057c7782cd5ad7a9fa00b8c5e0 to your computer and use it in GitHub Desktop.
Save igarag/f57022057c7782cd5ad7a9fa00b8c5e0 to your computer and use it in GitHub Desktop.
Convert list of lists or nested list to flat list (without brackets).
"""
(Does not work on python2)
Input example:
--------------
main_list =
[
[[3, 100, 37, 142, 96]],
[[3, 246, 37, 290, 97], [3, 101, 37, 143, 96]],
[[1, 194, 6, 233, 73], [1, 156, 6, 195, 72], [3, 246, 38, 290, 99], [3, 102, 39, 146, 98], [4, 85, 74, 133, 115], [7, 284, 168, 355, 236]],
[[1, 193, 7, 231, 72], [1, 156, 6, 194, 72], [2, 128, 11, 164, 79], [3, 245, 41, 288, 103], [3, 100, 39, 144, 99], [4, 262, 73, 316, 119], [4, 83, 74, 130, 115], [7, 35, 193, 99, 262], [7, 284, 169, 355, 237], [7, 42, 160, 105, 224], [8, 35, 205, 99, 254]],
[[1, 193, 6, 231, 72], [1, 155, 6, 193, 72], [2, 223, 13, 261, 77], [2, 127, 17, 164, 80], [3, 244, 41, 287, 104], [3, 99, 39, 143, 99], [4, 258, 74, 315, 122], [4, 83, 72, 130, 118], [5, 270, 104, 327, 140], [6, 40, 157, 104, 221], [7, 42, 158, 106, 223], [7, 35, 195, 100, 265]],
]
"""
for chunk in main_list:
for elem in chunk:
print(*elem, sep=' ')
# Or saving in other list:
flat_list = []
for elem in listOfList:
flat_list.extend(elem)
"""
Output:
--------
3 100 37 142 96
3 246 37 290 97
3 101 37 143 96
1 194 6 233 73
1 156 6 195 72
3 246 38 290 99
3 102 39 146 98
4 85 74 133 115
7 284 168 355 236
1 193 7 231 72
1 156 6 194 72
2 128 11 164 79
3 245 41 288 103
3 100 39 144 99
4 262 73 316 119
4 83 74 130 115
7 35 193 99 262
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment