I have a python list of lists that includes integers and I need to convert it into a single list.
If the list did not include any integers (only other lists) I could use the solution provided here: Making a flat list out of list of lists in Python
i.e.,
[item for sublist in main_list for item in sublist]
e.g,
test_list = [[1,2,3,4,5,6], [7,8,9,10], [11,12,13,14]]
test_list = [item for sublist in test_list for item in sublist]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
However, this solution does not work if the list has integers in it:
test_list_2 = [[1,2,3,4,5,6], 0, [7,8,9,10], [11,12,13,14]]
test_list_2 = [item for sublist in test_list_2 for item in sublist]
Traceback (most recent call last):
File "<ipython-input-28-c6531e09f706>", line 1, in <module>
test_list_2 = [item for sublist in test_list_2 for item in sublist]
TypeError: 'int' object is not iterable
Is there a way to circumvent this problem? Thanks.