Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


What 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:


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.


1 Answer

You 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)