Most developers write twenty lines to flatten nested lists. This one-liner does it in seconds — using recursion and comprehensions. You’ll learn how Python’s generator expressions handle arbitrary nesting depth cleanly.
▶ Final output when you run this code:
[1, 2, 3, 4, 5, 6]
📋 Code explained line by line:
1. def flatten(lst):
→ creates the callable function object flatten ready for later invocation with a list argument
2. return [x for item in lst for x in (flatten(item) if isinstance(item, list) else [item])]
→ produces a one-dimensional list with all nested elements extracted, so that when called with [1,[2,3,[4,5]],6] it returns [1,2,3,4,5,6]
4. nested = [1, [2, 3, [4, 5]], 6]
→ creates the variable nested holding [1, [2, 3, [4, 5]], 6] for immediate use in the subsequent call
5. print(flatten(nested))
→ outputs the sequence of integers 1 through 6 in order without any nesting
In questa pagina del sito puoi guardare il video online Python One-Liner Flattens Any Nested List della durata di ore minuti seconda in buona qualità , che l'utente ha caricato ZassTech Dev 03 agosto 2026, condividi il link con amici e conoscenti, su youtube questo video è già stato visto volte e gli è piaciuto 0 spettatori. Buona visione!