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
An alternative solution using a generator:
import collections
def flatten(iterable):
for item in iterable:
if isinstance(item, collections.Iterable) and not isinstance(item, str): # `basestring` < 3.x
yield from item # `for subitem in item: yield item` < 3.3
else:
yield item
>>> list(flatten([[1, 2, 3], [4, 5, 6], 7, 8]))
[1, 2, 3, 4, 5, 6, 7, 8]