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

Emmet Lowry
10,196 PointsPython collections. random choice challlange
Could someone explain this challenge to be bit by bit not understanding it thanks.
3 Answers

Jack Stout
2,796 PointsFrom the challenge...
"Create a function named nchoices()
that takes an iterable and an integer. The function should return a list of n
random items from the iterable where n
is the integer. Duplicates are allowed."
The first thing to note is that your function needs to take an iterable and an integer, then return a list.
def nchoices(things, n):
# your code here
return new_list
The lesson has been about the random.choice
function, so we can assume that we'll need to randomly choose the contents of our new_list
by applying the random.choice
function to our things
. The challenge also says that it should "return a list of n
random items". So, we probably want to apply the random.choice
function to things
enough times to fill the new_list
and stop when its length is equal to n
.
I won't give you a solution, but this is the kind of output you can expect...
>>> nchoices(['a', 'b', 'c'], 4)
['a', 'c', 'b', 'c']
>>> nchoices([1, 2, 3, 4, 5], 3)
[5, 2, 4]
Notice also that you probably won't get the exact results I did. While the length of the output should be exactly n
, the contents of the list will be random. And remember, "Duplicates are allowed." Don't spend any extra effort checking the list to see if it already contains a specific member.

Emmet Lowry
10,196 PointsThanks for the help was wondering could u explain how enumerate works. Just can wrap my head around the concept. Thanks

Jack Stout
2,796 PointsYa! enumerate
takes an iterable and returns a new iterable. The new one won't be a list, string, or any other type of iterable you're used to; it'll be an enumerate object, which is kind of weird. Fortunately, it's weirdness doesn't matter. The new iterable can be used the same as every other kind, it just doesn't print out very pretty.
It's used specifically for numbering items and will give a sequence of tuples where each tuple contains an integer and a corresponding item from the original iterable. Here's a little example...
>>> e = enumerate(['a', 'b', 'c'])
>>> for item in e: print(item)
...
(0, 'a')
(1, 'b')
(2, 'c')

Emmet Lowry
10,196 Pointsok thanks for that i think i understand it more now .