Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Unzipping Simple List-Like Objects

Credit: gyro funch

Problem

You have a sequence and need to pull it apart into a number of pieces.

Solution

There’s no built-in unzip counterpart to zip, but it’s not hard to code our own:

def unzip(p, n):
    """ Split a sequence p into a list of n tuples, repeatedly taking the
    next unused element of p and adding it to the next tuple.  Each of the
    resulting tuples is of the same length; if p%n != 0, the shorter tuples
    are padded with None (closer to the behavior of map than to that of zip).
        Example:
        >>> unzip(['a','b','c','d','e'], 3)
        [('a', 'd'), ('b', 'e'), ('c', None)]
    """
    # First, find the length for the longest sublist
    mlen, lft = divmod(len(p), n)
    if lft != 0: mlen += 1

    # Then, initialize a list of lists with suitable lengths
    lst = [[None]*mlen for i in range(n)]

    # Loop over all items of the input sequence (index-wise), and
    # Copy a reference to each into the appropriate place
    for i in range(len(p)):
        j, k = divmod(i, n)    # Find sublist-index and index-within-sublist
        lst[k][j] = p[i]       # Copy a reference appropriately

    # Finally, turn each sublist into a tuple, since the unzip function
    # is specified to return a list of tuples, not a list of lists
    return map(tuple, lst)

Discussion

The function in this recipe takes a list and pulls it apart into a user-defined number of pieces. It acts like a sort of reverse zip function (although it deals with only the very simplest cases). This recipe was useful to me recently when I had to take a Python list and break ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata