Content · Programming · Python

Python Lists: Combine and Flatten Nested Sequences

Flattening combines nested sequences into a single-level list. A nested loop or comprehension preserves order and handles empty sublists predictably. See two practical examples, edge cases and common mistakes.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A course collects student IDs in separate class groups.

What You Need to Understand


Flattening combines nested sequences into a single-level list. A nested loop or comprehension preserves order and handles empty sublists predictably.

When to Use It


A course collects student IDs in separate class groups.

Step-by-Step Python Example


class_groups = [[101, 102], [], [103, 104]]
all_students = []
for group in class_groups:
    all_students.extend(group)
print(all_students)

How the Example Works


Each group contributes its members; the empty group adds nothing. The final list contains all four IDs.

Example Output


[101, 102, 103, 104]
[1, 2, 3]

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

groups = [[1, 2], [3]]
print([value for group in groups for value in group])

Important Behavior and Edge Cases


This is only one-level flattening. Strings are iterables too and will split into characters if incorrectly extended.

Try It Yourself


Rewrite the flattening loop as a nested comprehension.

Common Beginner Mistakes


  • This is only one-level flattening. Strings are iterables too and will split into characters if incorrectly extended.
  • Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.

Key Takeaways


  • Flattening combines nested sequences into a single-level list.
  • Each group contributes its members; the empty group adds nothing.
  • This is only one-level flattening.
Share this resourceSend this page to someone who may find it useful.