Beginner Python Exercises

Flatten a Nested List

A nested comprehension can traverse groups and their items.

What is Flatten a Nested List?

A nested comprehension can traverse groups and their items.

Flatten a one-level nested list.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
nested = [[1, 2], [3, 4], [5, 6]]
# Read every value from every inner list.
flattened = [value for group in nested for value in group]
print(flattened)

Expected output

[1, 2, 3, 4, 5, 6]

How it works

The outer loop visits each group and the inner loop emits each value.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →