114

If I had two strings, 'abc' and 'def', I could get all combinations of them using two for loops:

for j in s1:
  for k in s2:
    print(j, k)

However, I would like to be able to do this using list comprehension. I've tried many ways, but have never managed to get it. Does anyone know how to do this?

John Howard
  • 61,037
  • 23
  • 50
  • 66

4 Answers4

173
lst = [j + k for j in s1 for k in s2]

or

lst = [(j, k) for j in s1 for k in s2]

if you want tuples.

Like in the question, for j... is the outer loop, for k... is the inner loop.

Essentially, you can have as many independent 'for x in y' clauses as you want in a list comprehension just by sticking one after the other.

To make it more readable, use multiple lines:

lst = [
       j + k         # result
       for j in s1   # for loop 
         for k in s2 # for loop
                     # condition   
       ]
Alex
  • 5,759
  • 1
  • 32
  • 47
aaronasterling
  • 68,820
  • 20
  • 127
  • 125
42

Since this is essentially a Cartesian product, you can also use itertools.product. I think it's clearer, especially when you have more input iterables.

itertools.product('abc', 'def', 'ghi')
miles82
  • 6,584
  • 38
  • 28
  • The Cartesian product is only a subset of the more general answer provided by @aaronasterling in which the inner loop values can be a function of each outer loop values. For example: for x in range(5) for y in range(x). – jpcgt Jun 01 '22 at 21:58
1

It's just a ready-to-go version of @miles82 answer (please give credit where it's due):

from itertools import product
list(map(list, product('abc', 'def') ))

Output:

[['a', 'd'],
 ['a', 'e'],
 ['a', 'f'],
 ['b', 'd'],
 ['b', 'e'],
 ['b', 'f'],
 ['c', 'd'],
 ['c', 'e'],
 ['c', 'f']]

In case you wondered why we need list(map(list - itertools.product returns an iterator.

mirekphd
  • 4,799
  • 3
  • 38
  • 59
0

Try recursion too:

s=""
s1="abc"
s2="def"
def combinations(s,l):
    if l==0:
        print s
    else:
        combinations(s+s1[len(s1)-l],l-1)
        combinations(s+s2[len(s2)-l],l-1)

combinations(s,len(s1))

Gives you the 8 combinations:

abc
abf
aec
aef
dbc
dbf
dec
def
Tshilidzi Mudau
  • 7,373
  • 6
  • 36
  • 49
Stefan Gruenwald
  • 2,582
  • 24
  • 30
  • Accourding to OP's question, I think the output should give couples of letters, and there should be 9 combinations. – Mattia Jul 30 '15 at 08:42
  • 1
    What happened to: abd, abe, acd, ace, acf, adb, adc, ade, adf, aeb, aed, afb, afc, afd, afe, and all the ones starting with c, e, or f? Even if order is not important, omitted are: bda, ade, etc. – Harry Binswanger Mar 26 '17 at 02:38
  • The way this works is, that the left most position can only be "a" or "d", the middle position can only be "b" or "e", and the right position can only be "c" or "f". – Stefan Gruenwald Mar 27 '17 at 22:31