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

I did not understand what i have to do here : "Create a function named nchoices() that takes an iterable and an integer"

i did not understand what is the task that the function should do here : "Create a function named nchoices() that takes an iterable and an integer. The function should return a list of n random items from the iterable where n is the integer. Duplicates are allowed." can someone clear it for me with an example of the input and expected output

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,064 Points

The Task: Create a function named nchoices() that takes an iterable and an integer. The function should return a list of n random items from the iterable where n is the integer.

Step by step this would be:

# Create a function named nchoices()....
def nchoices():
    pass

# that takes an iterable and an integer [as arguments]
def nchoices(iter1, num):
    pass

# The function should return a list....
def nchoices(iter1, num):
    new_list = []
    return new_list

# of n random items from the iterable where n is the integer.**
def nchoices(iter1, num):
    new_list = []
    # add num random items from iterable to new_list
    for _ in range(num):
        new_list.append(random.choice(iter1))
    return new_list

thank you Mr. Chris, that worked after i imported random