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 trialJason Pallone
895 Pointsrandom number from interable?
i'm lost, i get lost with these challenges and that worries me because i get the course work but i get lost on the challenges.. im not sure what to do here?
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(iterable)
random.randint(len(interable - 0 -= 1)
return(index)
2 Answers
Craig Dennis
Treehouse TeacherI see two problems. The term is iterable
as in able to iterate. I see a place where you have misspelled that.
What is happening with the line return(index)
What is index there?
I think you want len(iterable) - 1
.
Let me know if those hints don't help get you heading in the right direction.
You got this!
Jason Pallone
895 Pointsimport random
def random_item(iterable)
random.randint(len(iterable) - 1
return(int)
is what i came up with, im pretty confused here. I dont know how to get the index out of it? I know what a index is and all that, But i have no clue how to get the index out of this
Craig Dennis
Treehouse TeacherTry just returning the result of random.randint
return random.randint(len(iterable) -1)
Jonathan Beard
1,681 PointsSolution:
import random
my_list = ['1', '2', '3', '4', '5', '6']
def random_item(x):
num = random.randint(0, (len(x) - 1))
return x[num]
random_item(my_list)
Jason Pallone
895 PointsJason Pallone
895 PointsYou've seen how random.choice() works. It gets a random member from an iterable (like a list or a string).
I want you to try and reproduce it yourself.
First, import the random library.
Then create a function named random_item that takes a single argument, an iterable. Then use random.randint() to get a random number between 0 and the length of the iterable, minus one. Return the iterable member that's at your random number's index.
Check the file for an example.