0

I need to create every combination for list1, but add list2 to every combination of list1.

For example, this creates a combination for every value for list1:

list1 = ["a", "b" , "c"]
list2 = ["d", "e"]
list(itertools.combinations(list1, 2))
[('a', 'b'), ('a', 'c'), ('b', 'c')]

But I would like the result to be:

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

I have tried these common approaches, but am getting undesired results:

list1 = ["a", "b" , "c"]
list2 = ["d", "e"]
print(list(itertools.combinations(list1, 2)).extend(list2))
None

print(list(itertools.combinations(list1, 2)) + list2)
[('a', 'b'), ('a', 'c'), ('b', 'c'), 'd', 'e']

print(list(itertools.combinations(list1, 2) + list2))
TypeError: unsupported operand type(s) for +: 'itertools.combinations' and 'list'

Any help would be appreciated. Thanks.

3
  • 2
    There's no such shortcut, best write a list comprehension. Commented Apr 13, 2021 at 16:32
  • I updated the code for with two different purposes! Commented Apr 13, 2021 at 16:44
  • How would you do it if your intermediate result [('a', 'b'), ('a', 'c'), ('b', 'c')] didn't come from using itertools.combinations? Commented Apr 13, 2021 at 16:47

1 Answer 1

1

You can first generate a tuple of size 2 combinations for each list separately, then compute the cartesian product of those to combination lists:

import itertools
list1 = ["a", "b" , "c"]
list2 = ["d", "e"]

iter1 = itertools.combinations(list1, 2)
iter2 = itertools.combinations(list2, 2)

# If you want to add a subset of size 2 from list 2: 
product = itertools.product(iter1, iter2)
answer = list(map(lambda x: (*x[0], *x[1]), product))
# [('a', 'b', 'd', 'e'), ('a', 'c', 'd', 'e'), ('b', 'c', 'd', 'e')]

However, if you want to add all elements of list2 you can use:

import itertools
list1 = ["a", "b" , "c"]
list2 = ["d", "e", "f"]

iter1 = itertools.combinations(list1, 2)

# If you want to add all elements of list2
product = itertools.product(iter1, [list2])
answer = list(map(lambda x: (*x[0], *x[1]), product))
# [('a', 'b', 'd', 'e', 'f'), ('a', 'c', 'd', 'e', 'f'), ('b', 'c', 'd', 'e', 'f')]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.