Lists
How to flatten a list in Python
Quick answer
Use a recursive function or list comprehension to flatten a list in Python, e.g. [x for sublist in lst for x in sublist].
def flatten(lst):
result = []
for sublist in lst:
if isinstance(sublist, list):
result.extend(flatten(sublist))
else:
result.append(sublist)
return resultThis function works by iterating over each element in the input list. If an element is a list itself, the function calls itself with that sublist. Otherwise, it appends the element to the result list. This approach wins because it handles nested lists of arbitrary depth. A real gotcha is that this function does not handle non-list inputs.
Variations
Alternate Approach
import itertools
flat_list = list(itertools.chain(*lst))requires pip install itertools
Safer Variant
def flatten(lst, max_depth=None, current_depth=0):
if max_depth is not None and current_depth >= max_depth:
return lst
result = []
for sublist in lst:
if isinstance(sublist, list):
result.extend(flatten(sublist, max_depth, current_depth + 1))
else:
result.append(sublist)
return resultadd max_depth param for safety
Related Pattern
def flatten_dict(d):
result = {}
for k, v in d.items():
if isinstance(v, dict):
result.update({f'{k}.{sk}': sv for sk, sv in flatten_dict(v).items()})
else:
result[k] = v
return resultsimilar pattern for dicts
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.