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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 14 views 0 copies

Python code

19 lines
Python 3.9+
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'), (2, 'b'), (3, 'c')]
    numbers, letters = unzip(pairs)
    print(f"First: {numbers}")
    print(f"Second: {letters}")

Output

stdout
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

  1. Use `zip(*pairs)` to achieve the same result in one line: `nums, letters = zip(*pairs)` (returns tuples)
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.