Welcome to the Treehouse Community
Looking to learn something new?
Enzie RiddleFront End Web Development Techdegree Graduate 19,278 Points
Index and rand.int
Here's the question:
You'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.
I'm not sure where I am supposed to go with the index. Also if you could tell me what else I am doing wrong that'd be great :) Thanks!
# EXAMPLE # random_item("Treehouse") # The randomly selected number is 4. # The return value would be "h" import random def random_item("Treehouse"): random.randint(0, len("Treehouse")) - 1 return index()
Evan Trimby5,381 Points
First, you don't want to put the string value as an argument to the function. If it did work it would always send the same value to the function. Use a variable name, you can use something descriptive like item_in or on a small function like this just a single letter. Second you find the index using the random.randint() method. Return the iterable "piece" at that location.