Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Remove Duplicate

import random

x = ['a','b','c','d','e','f', 'g'] f = ['Jan','Feb','Mar','Apr','May','Jun']

shuffle1 = random.shuffle(x)

for i in x: print(f'{random.choice(x)}, {random.choice(f)}')

my goal is to print the list without duplicate each item in x appears at once, and each item in f appears at once as well. I tried, random.sample and random.choice, both pick duplicate items.

I really appreciate your help, I am really curious about how to do it.

1 Answer

Megan Amendola
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree seal-36
Megan Amendola
Treehouse Teacher

Random will always choose a random item from the list so there is always the possibility of it choosing the same item more than once. In order to make sure you don't get the same item again, you can remove items as they are chosen. Then you will get a random item from the list and make sure it cannot be chosen again.

x = ['a','b','c','d','e','f', 'g']
rand_choice = random.choice(x)
x.remove(rand_choice)

For example: I am able to get the first column not duplicated. But the second column is still duplicate, when I do y.remove(d), it gives me an error
y.remove(d)
ValueError: list.remove(x): x not in list how can I delete the item that is already selected in list x and y?

import random

x = ['a','b','c','d','e','f', 'g'] y = ['z', 'n', 'm', 'l', 'o', 'p']

while len(x) > 0: z=[] z = random.choice(x) d = random.sample(y, 1) print(z, d) x.remove(z)