1

Let us have a list of strings: fruit = ["apple", "orange", "banana"]. I would like to have an output that prints out all the possible pairs, i.e.

apple - apple, apple - orange, apple - banana, 
orange - orange, orange - banana, 
banana - banana

My idea was to enumerate fruit and do the following:

for icnt, i in fruit:
    jcnt = icnt
    j = i
    print ("icnt: %d, i: %s", icnt, i)
    for jcnt, j in fruit:
        print ("i: %s, j: %s", i, j)

Expectantly the string does not start from the icnt-th position but from the start. How to make the second loop to start from the i-th string?

2
  • use itertools.combinations Commented Jan 11, 2017 at 15:08
  • As @Jean-FrançoisFabre says, you should use itertools.combinations but to answer your question, you have to slice the fruit list in the second loop like so: for jcnt, j in enumerate(fruit[icnt:]): Also if you are going to use enumerate, do so. Commented Jan 11, 2017 at 15:11

2 Answers 2

3

use itertools.combinations_with_replacement to do this:

import itertools

for a,b in itertools.combinations_with_replacement(["apple", "orange", "banana"],2):
    print("{} - {}".format(a,b))

output:

apple - apple
apple - orange
apple - banana
orange - orange
orange - banana
banana - banana

or itertools.combinations if you don't want any repeats:

apple - orange
apple - banana
orange - banana

BTW your fixed code would look like this with enumerate:

fruit = ["apple", "orange", "banana"]

for icnt, i in enumerate(fruit):
     for jcnt in range(icnt,len(fruit)):
        print ("{} - {}".format(i, fruit[jcnt]))
Sign up to request clarification or add additional context in comments.

Comments

2

Don't reinvent the wheel. Use itertools:

from itertools import combinations_with_replacement

fruit = ["apple", "orange", "banana"]

print('\n'.join((' - '.join(perm) for perm in combinations_with_replacement(fruit, 2))))
# apple - apple
# apple - orange
# apple - banana
# orange - orange
# orange - banana
# banana - banana

2 Comments

This isn't exactly what is shown in the OP e.g you don't have apple-apple
@MosesKoledoye Thanks. got that fixed

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.