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

Stephen Poole
Stephen Poole
9,361 Points

Don't understand what is wrong with my code... Please help!

import random

def nchoices(iterate, integer): newList = [] while True: newList.append(random.choice(iterate)) if newList.length == integer: break return newList

choices.py
import random

def nchoices(iterate, integer):
  newList = []
  while True:
    newList.append(random.choice(iterate))
    if newList.length == integer:
      break

  return newList

2 Answers

Cody Te Awa
Cody Te Awa
8,820 Points

It appears as though you are trying to access a property from the list class on your list which is the length. To get a length of a list in python you use a function len(). So in this case to get the length of newList you would call len(newList). Hope this helps! Also just for pythonic coding: You could have that while loop in one statement by having in your while statement, while len(newList) < integer: ....etc

just something to ponder (:

Stephen Poole
Stephen Poole
9,361 Points

Thanks Cody! Works perfectly! :)

Rafael Valera
Rafael Valera
8,401 Points

You can do it with a for loop too, without having to check for conditions: for item in range(integer): new_list.append(random.choice(iterable))