Combinations between elements in two tuples in Python

Question:

I have two tuples:

t1 = ('A', 'B')
t2 = ('C', 'D', 'E')

I wonder how to create combinations between tuples, so the result should be:

AC, AD, AE, BC, BD, BE

EDIT

Using

list(itertools.combinations('abcd',2))

I could generate list of combinations for a given string:

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]

If I insert tuple instead of string the following error occurs:

TypeError: sequence item 0: expected string, tuple found

Any suggestion how to proceed?

Asked By: Andrej

||

Answers:

for value_one in t1:
    for value_two in t2:
        result = (str(value_one), str(value_two))
        print result

This uses no external libraries. Literally just two for loops and string concatenation. Format the output however you’d like.

This seems like you either did not put any effort into finding this answer, or I am misinterpreting the question.

Edit: I see that you are coming from an R background, so you may not understand Python syntax. Please refer to guides for Python basics; I believe they will help greatly. To save the values from the loop, as @Naman mentioned, you will want to make an empty list and [list_name].append([value]) the desired values, then print the values in the list using other constructs.

Answered By: Matthew R.

Here is my simple method:

for i in t1:
    for j in t2:
        print(i+j,end="")

This three line of input gives the above combinations.

Answered By: user2738777

You can print what you want by iterating over both the tuples(or make an empty list and store your output in that list)

l = []
for c1 in t1:
    for c2 in t2:
        print c1 + c2 + ',',
        l.append(c1 + c2)

Finally list l will contain the output elements. You can process its elements or make a tuple of it by

t = tuple(l)
Answered By: Naman Sogani
t = []
for x in t1:
    for y in t2:
        t.append(x+y)

t = tuple(t)

So iterate over both tuples, append every combination to a list and then convert the list back to a tuple.

Answered By: Dakkaron

All possible combinations:

import itertools

t1 = ('A', 'B')
t2 = ('C', 'D', 'E')

print(tuple(itertools.combinations(t1 + t2, 2)))

Output: (('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E'), ('D', 'E'))

Answered By: Red Shift

itertools.product does exactly what you are looking for:

>>> import itertools
>>> t1 = ('A', 'B')
>>> t2 = ('C', 'D', 'E')
>>> list(itertools.product(t1, t2))
[('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('B', 'D'), ('B', 'E')]
>>> [''.join(x) for x in itertools.product(t1, t2)]
['AC', 'AD', 'AE', 'BC', 'BD', 'BE']
Answered By: ThiefMaster
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.