3
votes

I have two lists:

frame = ["mercury", "noir", "silver", "white" ] 
seat_colors = [ 
            "coconut white", "yello", "black", "green", "cappuccino", 
            "orange", "chrome", "noir", "purple", "pink", "red", 
            "matte", "gray", "bermuda blue" 
                                            ]

I'm trying to combine them to a single list where every frame is uniquely matched with every seat color.

I'd like to use zip() like so:

In [3]: zip(frame, colors)

Out[3]:
[('mercury', 'coconut white'),
 ('noir', 'yello'),
 ('silver', 'black'),
 ('white', 'green')]

But it truncates to the length of the smallest list.

I know I can iterate through the lists with:

In [5]:

for f in frame:
    for c in colors:
        print "%s, %s" %(f, c)

Out [5]:
mercury, coconut white
mercury, yello
mercury, black
mercury, green
mercury, cappuccino
mercury, orange
mercury, chrome
mercury, noir
mercury, purple
mercury, pink
mercury, red
mercury, matte
mercury, gray
mercury, bermuda blue
noir, coconut white
noir, yello
noir, black
noir, green
....

But I'd like the to be smarter about it and use the power of python's built in functions.

Any ideas how to use zip ( or something like zip ) and avoid truncation?

2
Wait, so do you want the two lists zipped or do you want the Cartesian product? - DSM
@DSM Cartesian product. Sorry for not being clear. - agconti

2 Answers

11
votes

Use itertools.izip_longest() to keep zipping until the longest sequence has been exhausted.

This uses a default value (defaulting to None) to stand in for the missing values of the shorter list.

However, your output is creating the product of two lists; use itertools.product() for that:

from itertools import product

for a_frame, color in product(frame, seat_colors):
    print '{}, {}'.format(a_frame, color)

The two concepts are quite different. The izip_longest() approach will produce len(seat_colors) items, while the product produces len(seat_colors) * len(frame) items instead.

4
votes

You can use itertools.product:

import itertools
for item in itertools.product(frame, seat_colors):
    print item

This produces the same results as your nested for loops.