From 097cd89af15c0638665fd74522c0b307e39f1ae3 Mon Sep 17 00:00:00 2001 From: realpython-bot Date: Fri, 24 Apr 2026 15:05:48 +0000 Subject: [PATCH] Add recursive and iterative flatten examples for python-flatten-list --- python-flatten-list/flatten_iterative.py | 15 +++++++++++++++ python-flatten-list/flatten_recursive.py | 12 ++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 python-flatten-list/flatten_iterative.py create mode 100644 python-flatten-list/flatten_recursive.py diff --git a/python-flatten-list/flatten_iterative.py b/python-flatten-list/flatten_iterative.py new file mode 100644 index 0000000000..19efe87a72 --- /dev/null +++ b/python-flatten-list/flatten_iterative.py @@ -0,0 +1,15 @@ +def flatten(nested): + flat = [] + stack = [iter(nested)] + while stack: + for item in stack[-1]: + if isinstance(item, list): + stack.append(iter(item)) + break + flat.append(item) + else: + stack.pop() + return flat + + +flatten([1, [2, [3, [4, [5, 6]]]], 7, [8, 9]]) diff --git a/python-flatten-list/flatten_recursive.py b/python-flatten-list/flatten_recursive.py new file mode 100644 index 0000000000..7d5786e3d4 --- /dev/null +++ b/python-flatten-list/flatten_recursive.py @@ -0,0 +1,12 @@ +def flatten(nested): + flat = [] + for item in nested: + if isinstance(item, list): + flat.extend(flatten(item)) + else: + flat.append(item) + return flat + + +nested = [1, [2, [3, [4, [5, 6]]]], 7, [8, 9]] +flatten(nested)