2

I have 3 lists:

['1','2']

['a','b','c']

['X','Y']

and the result I am looking to get:

['1aX','1bX','1cX','2aX','2bX','2cX','1aY','1bY','1cY','2aY','2bY','2cY']

is there a way to set this up quickly?

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    possible duplicate of [Get the cartesian product of a series of lists in Python](http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python) – Felix Kling Jul 26 '12 at 18:55
  • I believe this operation is called the cartesian product of sets. Felix is a ninja. – Wug Jul 26 '12 at 18:55

3 Answers3

10

You can use itertools.product():

map("".join, itertools.product(list1, list2, list3))
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
2
>>> x,y,z=['1','2'],['a','b','c'],['x','y']
>>> s=[a+b+c for c in z for a in x for b in y]
>>> s
['1ax', '1bx', '1cx', '2ax', '2bx', '2cx', '1ay', '1by', '1cy', '2ay', '2by', '2cy']

This way you can choose the order you want

elssar
  • 5,651
  • 7
  • 46
  • 71
1

To get the exact result that you specified, you can use the following:

import operator
import itertools

list1 = ['1','2']
list2 = ['a','b','c']
list3 = ['X','Y']
getter = operator.itemgetter(1, 2, 0)
result = [''.join(getter(seq)) for seq in itertools.product(list3, list1, list2)]

The final argument to itertools.product() will be the first to change, so based on your example output we want list2 to be last, then list1, and then list3, since first the middle element advances, then the first element, then the last. The operator.itemgetter() call is used to reorder the elements so that the element from list1 comes first, etc.

I find list comprehensions easier to read here, but here is a one-line alternative that uses map():

map(''.join, map(operator.itemgetter(1, 2, 0), itertools.product(list3, list1, list2)))

(You could do the list comprehension in one line as well, but you shouldn't because then the operator.itemgetter() call would be executed on each iteration)

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306