Looping in python, Don’t want getting the same result from the loop [closed]

Currently i’m studying data science, and really start this from zero i’m trying to practice several things on Python right now

in this case i’m getting a category and should create a bundle

list_category = ['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10']

and in this context i want to get the result with this expectation:

a. not getting the same result in the bundle e.g (c1,c1,c1)
b. one bundle is allowed getting same two category e.g (c1,c2,c1)
c. same result with different order isn’t allowed e.g (c1 - c2 - c3 = c2 - c1 - c3)

i tried to using this code, but apparently i’m still getting a lot of same result

list_category = ['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10']
bundling_list = []
for i in list_category:
   category1 = i
   for y in list_category:
       if i != y:
           category2 = y
           for c in list_category:
               if c != y:
                   category3 = c
                   bundling = i + '-' + y + '-' + c
               
               bundling_list.append(bundling)
               
print(bundling_list)

tried to google some, but i didn’t get my expected answer so far, is there anyway to solve this Thanks!

Answer

Just import random module from python and use random.choice method to select a random item from your list.Then by creating a new list by avoiding that selected item.In this way 3 unique items can be collected from a list.

  • You can also simply delete items chosen using random from the list thereby avoiding creation of 2 extra lists.

I Think This may help you 🙂

import random
list_category = ['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10']
l2=[]
l3=[]
n1=random.choice(list_category)
for i in list_category:
    if i!=n1:
        l2.append(i)
n2=random.choice(l2)
for i in l2:
    if i!=n2:
        l3.append(i)
n3=random.choice(l3)
bundle="-".join([n1,n2,n3])
print(bundle)