-1

I've searched high and low for a solution for my script, but with no luck.

I am trying to print every possible duo from a given list. Except, not printing duplicates such as (a, a). And not printing a combination twice such as if (a, b) has been printed, then (b, a) will not be printed.

FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
    "Pistachio",
    "Raspberry",
    "Strawberry",
    "Vanilla",
]

for i in FLAVORS:
    for j in FLAVORS:
        if (i != j) :
            print(i, j, sep=", ")

I've managed to not print duplicates such as (a, a). However, I am stuck on how to print a combination only once so if (a, b) is printed, (b, a) wont be printed.

  • 1
    You're probably looking for [`iterools.combinations()`](https://docs.python.org/3/library/itertools.html#itertools.combinations) – ti7 Jul 28 '21 at 17:09
  • 1
    what is a and b? – deadshot Jul 28 '21 at 17:10
  • 3
    Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – ti7 Jul 28 '21 at 17:10

3 Answers3

1

You can use itertools.combinations

import itertools
FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
    "Pistachio",
    "Raspberry",
    "Strawberry",
    "Vanilla",
]
x=list(itertools.combinations(FLAVORS,2))
print(x)
  • Thank you, this worked great. I was specifically looking for the for loop way, to practice for loops, but I will take not of this. Thanks again. – AndrewGLeong Jul 28 '21 at 20:12
0

Something like that?

FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
]
n = len(FLAVORS)

for i in range(n):
    for j in range(i+1, n):
        print(FLAVORS[i], FLAVORS[j], sep=", ")
Banana, Chocolate
Banana, Lemon
Chocolate, Lemon
Gaëtan
  • 198
  • 7
0

Here is the solution

FLAVORS = [
    "Banana",
    "Chocolate",
    "Lemon",
    "Pistachio",
    "Raspberry",
    "Strawberry",
    "Vanilla",
]

for i in range(len(FLAVORS)):
    for j in range(i+1,len(FLAVORS)):
        print(FLAVORS[i],FLAVORS[j],sep=",")
Lakshika Parihar
  • 1,017
  • 9
  • 19
  • Thank you, this is exactly what I wanted. Can you explain the for loop code, please? How does that work in terms of knowing not to print duplicates and duos? – AndrewGLeong Jul 28 '21 at 20:11
  • 1
    Ah, I've got it not. I used http://pythontutor.com/visualize. I tried this earlier and it was printing out the number of the item rather than the item. I see you need to put FLAVOURS[i] to print it out :) thank you thank you thank you – AndrewGLeong Jul 28 '21 at 20:18