1

My question is very simple:

I have A = ['AA','BB'], B = ['CC','DD']

How do I get AB = ['AACC','AADD','BBCC',BBDD']?

Thank you!

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
g_tenga
  • 51
  • 7

3 Answers3

2

with list comprehension:

AB = [x + y for x in A for y in B]

we thus iterate over the elements in A and for each element x in A, we iterate over B, and then add x + y to the list.

Or for a variadic number of lists, and with a generator:

from itertools import product

map(''.join, product(A, B))

This can be easily extended to a variable number of elements, like:

>>> A = ['AA','BB']; B = ['CC','DD']; C = ['EE', 'FF']
>>> list(map(''.join, product(A, B, C)))
['AACCEE', 'AACCFF', 'AADDEE', 'AADDFF', 'BBCCEE', 'BBCCFF', 'BBDDEE', 'BBDDFF']
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

You can use itertools.product:

>>> from itertools import product
>>> A = ['AA','BB']
>>> B = ['CC','DD']
>>> AB = [''.join(p) for p in product(A, B)]
>>> AB
['AACC', 'AADD', 'BBCC', 'BBDD']

This has the benefit of working with any number of iterables.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

Its easier to see whats happening in a complete loop, here we are going to take i in a which will be AA and BB and j in b which will be CC and DD. On our first iteration we combine the first two AA + CC then append them to our new list , next comes AA + DD then onto BB and the process repeats.

a = ['AA','BB'] 
b = ['CC','DD']

res = []
for i in a:
    for j in b:
        x = i + j
        res.append(x)
print(res)
# ['AACC', 'AADD', 'BBCC', 'BBDD']

After you understand this you can skip that process and do it with list comprehension, this is identical.

res = [i + j for i in a for j in b]
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20