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

choices.py - Random Choices

Not exactly sure what the prompt is asking for

choices.py
import random

def nchoices(itb, n):
  new_list = []
  for n in itb:
    new_list.append(random.choice(itb))
  return new_list

3 Answers

Kourosh Raeen
Kourosh Raeen
23,732 Points

The for loop should do n iterations. You could do something like:

import random

def nchoices(itb, n):
  new_list = []
  for i in range(0, n):
    new_list.append(random.choice(itb))
  return new_list

interesting. So why is "0" used in range(0, n)?

Also, why is a new iterable ('i') used? I thought that you needed to use whichever iterable that is referenced in a for clause (or expression) inside the loop statement? I see that I was wrong about that. Could you explain this a bit or elaborate on your logic here in your code? THANK YOU!

Kourosh Raeen
Kourosh Raeen
23,732 Points

I use 0 because range(0, n) goes to n-1 so to have the loop iterate n times I started at 0. The variable i is just a counter and there is no other use for it inside the loop. We just need to execute the statement:

new_list.append(random.choice(itb)) 

n times.