

There are some differences in the implementation and the perks of generators vs iterators. Similar to itertools.chain, flatten returns a generator instead of a list. However, chain also comes with a couple of limitations: it concatenates a list of iterables but does not unwrap further, and it also requires all elements to be iterables: from itertools import chain l =, ]] list(chain(*l)) # ] l = ]] list(chain(*l)) # TypeError: 'int' object is not iterable Candidate Solution: PandasĪs an alternative to itertools.chain, pandas has a flatten function under.

from itertools import chain l =, ] list(chain(*l)) # list(om_iterable(l)) # Hence, you would need to cast it into a list explicitly if you would need more than just an iterator. A chain object can be understood as an iterator that iterates through each of the iterables. Among them is a function called chain which creates a chain object that concatenates a list of iterables. Itertools is one of Python’s standard libraries that provide handy functions that create iterators for efficient looping. Is there a more efficient way to flatten nested lists? Candidate Solution: itertools That would also mean that we need to run unwrap for however many nested layers there is. Theoretically, we can peel the list layer by layer like an onion: l = ]] from collections import Iterable def unwrap(l): flat_list = for item in l: if isinstance(item, Iterable): flat_list.extend(item) else: flat_list.append(item) return flat_list l = unwrap(l) # ] l = unwrap(l) # We have all dealt with lists of lists or even worse: lists of nested lists. In this blog, we will look into how to flatten lists. Welcome to a series of short posts each with handy Python tricks that can help you become a better Python programmer. Are you still iterating through for loops?
