1

I am trying to combine 2 lists and want to form combinations.

a = ['ibm','dell']
b = ['strength','weekness']

I want to form combinations like ['ibm strength','ibm weekness','dell strength','dell weakness'].

I tried to use zip or concatenated the lists. I also used itertools but it doesn't give me desired output. Please help.

a = ['ibm','dell']
b = ['strength','weekness']
c = a + b
itertools.combinations(c,2)
for a in a:
    for b in b:
        print a +b
0

2 Answers 2

6

You're looking for product(). Try this:

import itertools

a = ['ibm', 'dell']
b = ['strength', 'weakness']

[' '.join(x) for x in itertools.product(a, b)]
=> ['ibm strength', 'ibm weakness', 'dell strength', 'dell weakness']

To loop over the results don't forget that itertools.product() returns an iterator that can be consumed only once. If you need it at a later time, convert it into a list (as I did above, using a list comprehension) and store the result in a variable, for future use. For example:

lst = list(itertools.product(a, b))
for a, b in lst:
    print a, b
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks oscar for the prompt response. also can you please explain why the list items start dissapearing when i loop over the items and join them. as in after i use loop the list gets empty
Is amazing this way Óscar! ;) Nice one!
@RaghavShaligram That doesn't happen to me … please post the code that's causing the problem. Also, you should save the list in a variable, for future usage
@ÓscarLópez i just updated the code and used a nested loop. The list items starts vanishing..
@RaghavShaligram You are not using the code in my answer … anyway, see my update. Remember that the functions in itertools return iterators (not lists), that can be traversed only once. If you need to use them at a later point convert them to lists. And you must save the result in a variable, simply calling the function won't do anything
|
0

For a Cartesian product, you want itertools.product() instead of combinations.

A nested for-loop would also work:

for x in a:
    for y in b:
        c = a + b
        print(c)

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.