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 trialEnas Sterjanaj
113 Pointshelp with iterables
I made the following function which seems to work with just having the function take n for the integer. Do i have to pass an itterable into the function to pass this section? How exactly do i do that?
Here is my code:
import random
n = int(raw_input("Please enter number of items to create: "))
def nchoices(n): L = [] my_list = range(n) for item in my_list: L.append(random.choice(my_list))
print(L)
return L
nchoices(10)
import random
#n = int(raw_input("Please enter number of items to create: "))
def nchoices(n):
L = []
my_list = range(n)
for item in my_list:
L.append(random.choice(my_list))
print(L)
return L
nchoices(10)
1 Answer
Dan Johnson
40,533 PointsYes, the iterable argument is required. It's needed since you're actually selecting choices from the iterable that is passed in, rather than a range. The integer argument represents how many times you want to randomly pick from the iterable that was passed in.
You don't have to change much with your code to get it to work:
def nchoices(iterable, n):
# I'd recommend against 'L' as a variable name in most cases
choices = []
for item in range(n):
# Select from the iterable
choices.append(random.choice(iterable))
return choices
Enas Sterjanaj
113 PointsEnas Sterjanaj
113 Pointsthanks for clearing this up.