I am trying to flatten a list using list comprehension in python. My list is somewhat like
[[1, 2, 3], [4, 5, 6], 7, 8]
just for printing then individual item in this list of list I wrote this code
def flat(listoflist):
for item in listoflist:
if type(item) != list:
print item
else:
for num in item:
print num
>>> flat(list1)
1
2
3
4
5
6
7
8
Then I used the same logic to flatten my list through list comprehension I am getting the following error
list2 = [item if type(item) != list else num for num in item for item in list1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
How can I flatten this type of list-of-list using using list comprehension ?
One-liner:
A readable version:
Using nested list comprehension:(Going to be slow compared to
itertools.chain
):An alternative solution using a generator:
You're trying to iterate through a number, which you can't do (hence the error).
If you're using python 2.7:
But do note that the module is now deprecated, and no longer exists in Python 3
No-one has given the usual answer:
There are dupes of this question floating around StackOverflow.