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 trialCeceilia Hedrick
2,220 PointsDragon Game challenge task 1 choices.py
Why does this code not return a list of random choices? The Bummer message isn't helpful this time :(
import random
def nchoices(list,int):
choices=[]
for i in range(int):
choices[i]=random.choice(list)
return choices
1 Answer
Ceceilia Hedrick
2,220 PointsI figured it out. I defined the choice list as an empty list i.e. choices = [ ]. Then in the for loop when I tried to add something to choices [0]= random.choice(list), I was already out of the choices list boundary. I fixed it with choices.append(random.choice(list)).
I guess I though python would be cool enough to realize I wanted to make my list bigger than null, but alas the programmer can never escape index out of bound errors.
Kenneth Love
Treehouse Guest TeacherYeah, this comes from Python's explicitness. Since the list is 0 items long, you can't assign to higher numbers because that would implicitly make the list bigger, without you explicitly adding new indexes to the list.
I see this as a good thing, mostly because it avoids the weird question of "what if I assign to my_list[50]
when my_list
only has 5 items in it?"
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi Ceceillia,
I fixed your code block for you.
Please see this thread for how to post code: https://teamtreehouse.com/forum/posting-code-to-the-forum