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

Python Python Basics (2015) Letter Game App Random Item

Random_item not defined

getting error random_item not defined.

item.py
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(iterable):
    return iterable.index(random.randint(0,len(iterable))-1)

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! It is, but I believe that your code is raising an exception. You're using the index method here, but that's not returning what you think it is. The index method is looking for an object inside an iterable and the object it's looking for is the random number that you've created. But if it can't find that number inside the iterable then an exception will be raised. You can find documentation on the index method for string here but other data types also have index methods.

The challenge wants you to get whatever object is at that index instead of getting the index of the *object. Remember, if we want to get the first item from an iterable, we can use the subscript notation like this:

my_string = "Hello"
my_letter = my_string[0]

At this point, my_letter would equal "H" as it is the letter at the 0 index. If we wanted to find the index of "H" we would do this:

my_index = my_string.index("H")

This would return a 0 and assign it to my_index as 0 is the index where "H" first occurs.

Hope this helps! :sparkles: