0

Lets say we have the following lists

lsta = ['a','b','c']
lstb = ['1','2','3','4']
lstc = ['x','y']

I'd like to make a function that can consume an arbitrary number of different lists and append them together in all combinations and in way that lista item always comes first, lstb item always comes second, and lstc item always comes third.

The result would be 24 combinations (3 items in first list, 4 items in second, and 2 items in third) of the above lists. For example, here would be a sample:

[['a1x','a2x','a3x','a4x','b1x','b2x','b3x'....]]
Chris
  • 5,444
  • 16
  • 63
  • 119

2 Answers2

6

This is a "Cartesian product", so you can use itertools.product:

>>> lsta = ['a','b','c']
>>> lstb = ['1','2','3','4']
>>> lstc = ['x','y']
>>> from itertools import product
>>> ["".join(t) for t in product(lsta, lstb, lstc)]
['a1x', 'a1y', 'a2x', 'a2y', 'a3x', 'a3y', 'a4x', 'a4y', 
 'b1x', 'b1y', 'b2x', 'b2y', 'b3x', 'b3y', 'b4x', 'b4y', 
 'c1x', 'c1y', 'c2x', 'c2y', 'c3x', 'c3y', 'c4x', 'c4y']

This will work however long each list is, or however many lists you have.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • `@jonrsharpe` : Nice snippet to do Cartesian product.Here you have used **lsta, lstb, lstc** but I have dynamic 2-D list such as `lst = [['a','b','c'], ['1','2','3','4'], ['x','y'], ['t','z']]` so how can I split this into individual list and use with **product()**. Can anyone help me? – iNikkz Nov 04 '14 at 06:19
  • 1
    @Nikkz just `product(*lst)` to unpack the sub lists – jonrsharpe Nov 04 '14 at 08:05
  • `@jonrsharpe:` Great! thanks. How it works? Can you explain me plz? – iNikkz Nov 04 '14 at 11:14
2
from itertools import product
lsta = ['a','b','c']
lstb = ['1','2','3','4']
lstc = ['x','y']
["".join(i) for i in product(lsta,lstb,lstc)]

Output

['a1x', 'a1y', 'a2x', 'a2y', 'a3x', 'a3y', 'a4x', 'a4y',
 'b1x', 'b1y', 'b2x', 'b2y', 'b3x', 'b3y', 'b4x', 'b4y',
 'c1x', 'c1y', 'c2x', 'c2y', 'c3x', 'c3y', 'c4x', 'c4y']
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218