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.
Python code
19 linesdef 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'), (2, 'b'), (3, 'c')]
numbers, letters = unzip(pairs)
print(f"First: {numbers}")
print(f"Second: {letters}")
Output
First: [1, 2, 3]
Second: ['a', 'b', 'c']
How it works
The for a, b in pairs loop unpacks each tuple into two variables, so you can append the first element to firsts and the second to seconds in every iteration. Returning [], [] early handles the empty-input case so the function always returns two lists. This manual loop is explicit and easy to read, making it a clear approach when you want full control over the splitting logic. The function returns a tuple of two lists, which can be assigned directly to two variables with numbers, letters = unzip(pairs).
Common mistakes
- Forgetting to handle an empty input list, which would cause the loop to return `None, None` instead of two lists
- Assuming the pairs are always tuples — the unpacking works with any two-element iterable, but fails if an element has a different length
- Mutating the original pairs list while iterating, which can skip elements or cause unexpected behavior
Variations
- Use `zip(*pairs)` to achieve the same result in one line: `nums, letters = zip(*pairs)` (returns tuples)
- Use a list comprehension with `enumerate` if you need indexes along with the split values
Real-world use cases
- Splitting a list of coordinate pairs into separate X and Y arrays before plotting charts.
- Separating key-value pairs fetched from a database into parallel lists for column-based processing.
- Dividing paired measurement data (e.g., time and value) into two columns for CSV export.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.