Created
March 17, 2019 09:13
-
-
Save ShyamaSankar/24cafba55fdd108638cdb9b73cb51251 to your computer and use it in GitHub Desktop.
Flatten list of list using list comprehension
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
# Our list of lists. | |
matrix = [[1,2,3], [4,5,6], [7,8,9]] | |
# For loop to flatten the matrix. | |
flattened_list = [] | |
for each_list in matrix: | |
for number in each_list: | |
flattened_list.append(number) | |
# Rewrite using list comprehension. | |
# Syntax: | |
# list_object = [expression_on_item_in_inner_iterable | |
# for_item_in_outer_iterable for_item_in_inner_iterable] | |
flattened_list = [number for each_list in matrix for number in each_list] | |
print(flattened_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment