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.

Python Python Collections (Retired) Dungeon Game Random Choices

Aarron Walter
Aarron Walter
2,217 Points

Random choices and looping

I'm stumped on this challenge. I need to build a list of random choices, but the number of choices is determined by an int passed into my function. Looping on that int the the part that is tripping me up.

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 67,986 Points

Here is the flow:

# remember to import random
import random

def nchoices(iter1, count):
    results = []
    # run loop 'count' times
    for _ in range(count):
        # append new random item from iter1 to results list
        results.append(random.choice(iter1))
    return results

Note that since I don't need the value of the loop variable, I used "_" as a "throw-away variable".

Aarron Walter
Aarron Walter
2,217 Points

Thanks, Chris! Looping on a range was exactly the answer I needed. I appreciate your help.