vendredi 18 octobre 2019

How to get ride of duplicate combinations when going through list in two for loops in python?

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? Thanks for the help!

Aucun commentaire:

Enregistrer un commentaire