Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
How to Flatten One Level of a Nested List in Python
Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.
def flatten_one_level(nested_list):
"""Flatten one level of a nested list."""
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(item)
else:
flattened.append(item)
return flattened
if __name__ == "__main__":
# Example with mi…
How to unzip a list of pairs into two lists in Python
Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.
def unzip(pairs):
"""Split a list of (a, b) pairs into two separate lists."""
if not pairs:
return [], []
firsts = []
seconds = []
for a, b in pairs:
firsts.append(a)
seconds.append(b)
return firsts, seconds
if __name__ == "__main__":
pairs = [(1, 'a'), (…
Browse by section
Each section groups closely related Python snippets.
Lists & loops — Python code examples
What you will find here
This page collects lists & loops snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.