How do I make a flat list out of a list of lists?
Quick and dirty list comprehension way to flatten a list of lists:
Just two lines of code, and you're already flattening like a pro π!
Digging into efficiency
Let's unwrap the box π of efficient techniques, to see how well they perform.
The sleek itertools.chain
Big lists don't scare you? itertools.chain.from_iterable()
might be your speed demon ποΈ:
Return of the iterator! This guy unwraps lists lazily, saving your precious memory footprint.
The lightning-fast reduce and concat
Combine functools.reduce()
with operator.iconcat
for electrifying speed β‘:
Say hello to your new best friend, speed!
Measure the horsepower with perfplot
One size doesn't fit all. Use 'perfplot' to benchmark execution speed. Nothing screams efficiency better than charts π:
Busting the inefficiency myths
Beware of sum(outer_list, [])
, it holds a dark secret of quadratic complexity (O(n^2)). Can be as slow as a snail π on large datasets due to list reallocation and copying.
Other flattening contestants
As they say, the more, the merrier! Let's meet our other contenders.
numpy's try
numpy
utilities for flattening lists might look tempting, but they are like a hungry Godzilla gobbling up your system resources π¦. Avoid unless numeric processing is already your playground.
The extend approach
A bit slower, but for a good reasonβeasy debugging and better readability:
Slow and steady does sometimes win the race π’.
Flattening lists with sublists
Nested lists? No problem! We have recursive flattening and itertools with unpacking on our side.
Recursive flattening
Shall we descend into the depths π of multi-level nested lists?
itertools and unpacking
A sophisticated technique using itertools.chain()
with the power of unpacking:
Beware, though: unpacking needs all sublists to be accessible in memory!
Was this article helpful?