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

item.py -- Question about my approach to solving the problem

"""So, I got the right answer to the code challenge, however, I felt like my approach was potentially different from that of other (more experienced) coders. """

import random

def random_item(it): random_index = random.randint(0, len(it) -1) random_item = it[random_index] return random_item

Did I add a superfluous variable? or is my approach palpable?

item.py
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random

def random_item(it):
    random_index = random.randint(0, len(it) -1)
    random_item = it[random_index]
    return random_item

2 Answers

Kourosh Raeen
Kourosh Raeen
23,733 Points

It looks good to me. The only change I'd make is to combine the last two lines into:

return it[random_index]

Yeah, that makes sense. Thank you!

Mike Tribe
Mike Tribe
3,827 Points

Or

def random_item(i):

  return i[random.randint(0, len(i))-1]
Wade Wilson
Wade Wilson
3,505 Points

I managed to have the same first three lines of code! progress!

unfortunately I'm totally lost on the last line. :(

why it[random_index]?

where did that come from?

Kourosh Raeen
Kourosh Raeen
23,733 Points

The function needs to return a random member of an iterable. The variable 'it' is the iterable passed into the function. random_index is a randomly selected index between 0 and the length of the iterable less one. So the last thing to do is to get the member at that random index, which is done by it[random_index] and then return it.

For example, if the iterable is the string "Python" and random_index turns out to be 3, then it[random_index] will get 'h' and then the function returns it.