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 trialMohammad Alawad
1,877 PointsWhat method in Random module can give a random number from a range inside a loop without repetition.
What method in Random module can give a random number from a range inside a loop so that it gives all numbers without repetition. for example:
example_list=[]
while len (example_list) <5: num=random.randrange (0,4) example_list.append (num)
I want example_list to have unique numbers from 0-4 but not repetid numbers. the list has to be 5 digits.
I was trying this but this method always gives repeated numbers.
thank you.
Regards,
1 Answer
Nathan Burnham
7,827 PointsYou can add an if statement to check whether or not the number is already in the list. Another thing you are going to want to do is change the randrange from (0, 4) to (0, 5) because the end number is not included in the range. As is, you'll have an infinite look because the while loop will never be False.
while len(example_list) < 5: num = random.randrange(0, 5) if num in example_list: pass else: example_list.append(num)