Python Practice › List Programs › Program 90

Flatten a nested list

MediumList Programs · 90 of 100

Write a Python program to flatten a nested list.

Advertisement
Input
[0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
Output
[0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]

Approach

  1. Add plain items directly and the contents of sub-lists one by one (recursively for deeper nesting).

Solution

Python
def flatten(items):    flat = []    for item in items:        if isinstance(item, list):            flat.extend(flatten(item))        else:            flat.append(item)    return flat print(flatten([0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]))
Output
[0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]

Line by line

Lines 4-5

A sub-list is flattened by calling the same function on it, so any depth works.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment