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 Python Collections (Retired) Dungeon Game Random Choices

Random selection not working?

Try as I might, The best error message I get is "where's nchoices()?" This looks like it should work, but maybe I'm missing something. Ideas?

Challenge: "Create a function that returns a list of random items from an iterable. The function, named nchoices(), should take an iterable and an integer for the number of items to return. Duplicates are allowed."

import random

def nchoices(iterable,num_items):
    list = []
    while len(list) < num_items:
      item = random.choice(iterable)
      list.append(item)

    return list

(Edited to add the random module import.)

3 Answers

Hi James,

I think all that you missed is that you didn't import the random module. Your code passes for me if I add that in.

You may want to use another name for your list variable inside the function though since that's a built-in type.

Also, if you've been introduced to range then you could set it up as for loop instead.

for _ in range(num_items):

Jason,

You're right--it worked. I "assumed" you never have to import modules when working in the code challenge editor, so it didn't even cross my mind. Live and learn.

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

You really think I won't make you do all of the work? :) You don't know me well enough, then.

Yep, thought of range(). For some reason, the while loop seemed simpler to me.