Home > Commands ->  Lists -> List Commands ->  zip


Syntax: zip(list_x, list_y) where list_x and list_y are lists with values (numbers) of equal length. (You can use more than 2 lists.)

     Returns a list of points (x,y) whose j-th element is the order pair of the j-th element from list_x and the j-th element from list_y.


  • Example 1
    x_d = [18,23,25,35,65,54]                  # ages of individuals
    y_d = [202,186,187,180,156,169]      # maximum heart rate of each one
    pts=zip(x_d,y_d)                                 #zip your two lists into a list of points, i.e. 2-tuples.
    print pts
    Result:
    [(18, 202), (23, 186), (25, 187), (35, 180), (65, 156), (54, 169)]

UNZIP Syntax: x_tup, y_tup=zip(*zipped_list) where zipped_list is a list of ordered pairs. (You can use a list of n-tuples.)

     Returns 2 m-tuples where m is the length of zipped_list.


  • Example 1
    z_list=[(18, 202), (23, 186), (25, 187), (35, 180), (65, 156), (54, 169)]
    x_tup, y_tup=zip(*z_list)
    print x_tup, y_tup
    x_list=list(x_tup); y_list=list(y_tup)
    print x_list, y_list
    Result:
    (18, 23, 25, 35, 65, 54) (202, 186, 187, 180, 156, 169)
    [18, 23, 25, 35, 65, 54] [202, 186, 187, 180, 156, 169]

    Comments: Notice the command list() makes a list out of a 1-tuple (parentheses have turned into brackets). Now you can extract x-coordinate of the 3rd point of z_list: eg. print x_list[2]


Related wikipages: Operations on Lists, Commands on Lists, append, sum

My Sagepage: Scatterplots


Official definition of zip: Return a list of 2-tuples, where the j-th element of the new list contains the j-th element from each of the 2 lists of 1-tuples.


Keywords: lists, combine, 1-tuples, 2-tuples, ordered pairs