0

I have a list and I want to get combinations of everything in my list. However, when using two for loops to do this, it gives me duplicate combinations.

fruits = ['apple', 'orange', 'pear', 'grape']
for x in fruits:
    for y in fruits :
        if x != y:
            print(x, y)

and I get

apple orange
apple pear
apple grape
orange apple
orange pear
orange grape
pear apple
pear orange
pear grape
grape apple
grape orange
grape pear

What I don't want is both

 apple orange
 orange apple

just one of the combinations is all I want.

apple orange
apple pear
apple grape
orange pear
orange grape
pear grape

Is there any way to do this using the if statement or within the for loop?

martineau
  • 119,623
  • 25
  • 170
  • 301
mjoy
  • 606
  • 2
  • 9
  • 19

3 Answers3

2

What you're looking for is all the combinations (of size 2), but you're printing permutations (of size 2). You can use itertools.combinations for this:

from itertools import combinations

fruits = ['apple', 'orange', 'pear', 'grape']
for x in combinations(fruits, 2):
    print(x)

EDIT:

You could do it with just for loops like this:

for i in range(len(fruits)):
    for j in range(i + 1, len(fruits)):
        print(fruits[i], fruits[j])
gstukelj
  • 2,291
  • 1
  • 7
  • 20
0
ans = []
fruits = ['apple', 'orange', 'pear', 'grape']
for x in fruits:
    for y in fruits :
        if x != y and (y, x) not in ans:
            ans.append((x,y))
print(ans)

Output:

[('apple', 'orange'), ('apple', 'pear'), ('apple', 'grape'), ('orange', 'pear'), ('orange', 'grape'), ('pear', 'grape')]
0

You can use a set of frozensets for look up:

fruits = ['apple', 'orange', 'pear', 'grape']
lookup = set()

for x in fruits:
    for y in fruits:
        combo = frozenset([x, y])
        if x != y and combo not in lookup:
            lookup.add(combo)
            print(x, y)
Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73