Wednesday, December 30, 2015

How to flatten a list of lists

flatten
In [1]:
#An example of how to flatten a list of lists.

#create lista and listb 
lista = ['a','b','c']
listb = ['d','e','f']

#create a combined list that needs to be flattened
combined_lists = []
combined_lists.append(lista)
combined_lists.append(listb)

#note that the items in lista and listb are in separate lists within a list.
print combined_lists
[['a', 'b', 'c'], ['d', 'e', 'f']]
In [2]:
#flatten the list of lists
flattened_list = [item for sublist in combined_lists for item in sublist]
flattened_list
Out[2]:
['a', 'b', 'c', 'd', 'e', 'f']