Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Enzie Riddle
Front End Web Development Techdegree Graduate 19,278 PointsIndex 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()
1 Answer

Evan Trimby
5,381 PointsFirst, 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.
Enzie Riddle
Front End Web Development Techdegree Graduate 19,278 PointsEnzie Riddle
Front End Web Development Techdegree Graduate 19,278 PointsI thought the directions said to use an iterable as the argument? Also, I'm not sure how to go from the random integer to the letter that corresponds to that index number.
Enzie Riddle
Front End Web Development Techdegree Graduate 19,278 PointsEnzie Riddle
Front End Web Development Techdegree Graduate 19,278 PointsOH. I understand now. Thank you!