To generate pairs iteratively, you need to look at the itertools.product function:
>>> l1 = [1, 2, 3] >>> l2 = [1, 3, 7] >>> import itertools >>> list(itertools.product(l1, l2)) [(1, 1), (1, 3), (1, 7), (2, 1), (2, 3), (2, 7), (3, 1), (3, 3), (3, 7)]
However, I do not consider it possible to remove duplicate pairs without tracking those that you have already seen.
To remove duplicates in memory, I would sort the tuples and make them a set:
>>> pairs = list(itertools.product(l1, l2)) >>> set(map(tuple, map(sorted, pairs))) set([(1, 2), (2, 7), (1, 3), (3, 3), (2, 3), (1, 7), (3, 7), (1, 1)])
If you want the memory to be low and you can use the disk, I would suggest using the merge sort supported by the disk files similar to this approach . When repeating the result of itertools.product pair and write it to disk. Then use merge sort and read the sorted list, removing duplicates (since they will be contiguous).