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

Spencer Heflin
Spencer Heflin
7,389 Points

Code Challenge for Random Item

Not exactly sure what's wrong with my code here. It just says bummer try again. I feel like it's something related to the last line, but any suggestions would be appreciated.

item.py
import random

def random_item(list):
    num = random.randint(0,3)
    return list.index(num)

3 Answers

Manish Giri
Manish Giri
16,266 Points

What I noticed -

  1. In your randint() function, you're passing arguments 0 and 3. Thereby you're assuming that the list will always contain only 4 elements. What if I call your function with a list that has just 2 elements? So, instead of using 3 as the second argument, use the len() function to find the length of the iterable and subtract 1 from it.
  2. In the last line, you're doing list.index(num). This looks for an element num in the list and returns the first index where it is found at. What you need to do is the opposite - return the element in the list that is present at the index which you generated using randint. HINT - how do you access list elements?
  3. Last, list is a reserved keyword in Python, would be better if you name your iterable something else, like lst, for example.
Spencer Heflin
Spencer Heflin
7,389 Points

Thanks a lot for your help Manish. I changed my code around and I think it's a lot closer. But now it's saying that I'm not getting a correct item back from my function. Can you see what I'm doing wrong? This is my code now: import random

def random_item(animals): animals = ['bears', 'tigers', 'dogs', 'cats'] num = random.randint(0, len(animals)-1) return animals[num]

Manish Giri
Manish Giri
16,266 Points

So, if your code is like this -

def random_item(animals): 
    animals = ['bears', 'tigers', 'dogs', 'cats'] 

You're overwriting the value of animals in your method.

Let's say I call your function with my own list, like random_item(["one", "two", "three", four"]). If you set animals to ['bears', 'tigers', 'dogs', 'cats'] in your code, you're essentially losing the list I called your function with.

So remove the assignment to animals and your should be fine -

def random_item(animals):
    num = random.randint(0, len(animals)-1) 
    return animals[num]
Spencer Heflin
Spencer Heflin
7,389 Points

That worked. I really appreciate your help.