How to flatten a list of list in Python?

Three different approaches for flattening a list of list in Python

  • input: [[1,2,3], [3,4,5]]
  • output: [1,2,3,3,4,5,]

list_of_list = [[1,2,3], [3,4,5]]

# 1st approach: using for loops
flattened_list = list()
for sub_list in list_of_list:
 for item in sub_list:
  flattened_list.append(item)
  
# 2nd approach: using single line for loops
flattened_list = [item for sub_list in list_of_list for item in sub_list]

# 3rd approach: using lambda function if you do many of 
# these operations for different list of list
flatten = lambda list_of_list: [item for sub_list in list_of_list for item in sub_list]
flattened_list = flatten(list_of_list)

# if you have many list of list to flatten, such as list_of_list1, list_of_list2
flattened_list1 = flatten(list_of_list1)
flattened_list2 = flatten(list_of_list2)
  

No comments:

Post a Comment