Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShyamaSankar/24cafba55fdd108638cdb9b73cb51251 to your computer and use it in GitHub Desktop.
Save ShyamaSankar/24cafba55fdd108638cdb9b73cb51251 to your computer and use it in GitHub Desktop.
Flatten list of list using list comprehension
# 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