Welcome, guest | Sign In | My Account | Store | Cart

This function 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).

Python, 20 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def unzip(p, n):
    """Split a list-like object, 'p', into 'n' sub-lists by taking
    the next unused element of the main list and adding it to the
    next sub-list. A list of tuples (the sub-lists) is returned.
    Each of the sub-lists is of the same length; if p%n != 0, the
    shorter sub-lists are padded with 'None'.
        Example:
        >>> unzip(['a','b','c','d','e'], 3)
        [('a', 'd'), ('b', 'e'), ('c', None)]
    """
    (mlen, lft) = divmod(len(p),n)          # find length of longest sub-list
    if lft != 0: mlen += 1

    lst = [[None]*mlen for i in range(n)]   # initialize list of lists 
        
    for i in range(len(p)):
        (j, k) = divmod(i, n)
        lst[k][j] = p[i]

    return map(tuple, lst)

This recipe was useful to me recently when I had to take a Python list and break it down into a number of different pieces, putting each consecutive item of the list into a separate sub-list.

1 comment

Cristian Sebastian Rocha 13 years, 5 months ago  # | flag

The best way to "unzip" a list is using the zip function in this way:

>>> A = [1,2,3]
>>> B = [4,5,6]
>>> Z = zip(A, B)
>>> Z
[(1, 4), (2, 5), (3, 6)]
>>> Ap, Bp = zip(*Z)
>>> Ap
(1, 2, 3)
>>> Bp
(4, 5, 6)

you can read more details in the zip documentation.

Created by gyro funch on Tue, 28 Aug 2001 (PSF)
Python recipes (4591)
gyro funch's recipes (6)
Python Cookbook Edition 1 (103)

Required Modules

  • (none specified)

Other Information and Tasks