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 trialAlex Rendon
7,498 Points"BUMMER expected a list, got <class: str>" Why this error appears, if the return is a list.
Is it a bug of the compilator of teamtreehouse? Or what is my error? help me please.
import random
itr=[1,2,3,4,5,6,7,8,9,10,11]
num=random.choice(itr)
def nchoices(itr,num):
return itr[:num]
2 Answers
William Li
Courses Plus Student 26,868 PointsHi, Alex, I think the logic of your code is a bit off here. This challenge asks you to write a function nchoices(), it takes 2 arguments, first argument is an iterable, e.g. list, string, tuple ... etc; 2nd argument is an integer.
For example, if the second argument is 10, you function needs to randomly pick a number from the iterable argument 10 times, and each time append the picked value to a new list.
Here's one way to do it.
import random
def nchoices(iterable, n):
# Create a function named nchoices() that takes an iterable and an integer(n).
# return a list of n random items from the iterable where n is the integer.
result = [] # empty list placeholder
while n > 0: # execute while loop as long as n is greater than 0
result.append(random.choice(iterable)) # pick one random item from iterable and append to result list
n -= 1 # decrement n by 1, so that n will eventually approach the loop termination condition.
return result # after the loop is finished, result list is the return value of this function.
Alexander Davison
65,469 PointsI have the answer! It wanted the list, not the list item. I hope that solved it! :D
Alex Rendon
7,498 PointsAlex Rendon
7,498 PointsHey William, thanks very much. You have helped me so much.