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

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,733 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,733 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.