views:

90

answers:

2

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?

+6  A: 
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

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

aaronasterling
+1 since the OP asked for LC's.
gnibbler
+5  A: 

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
+1 because product is a nicer answer than LC's for this
gnibbler