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

Alejandro Byrne
Alejandro Byrne
2,562 Points

Need help on this challenge. Don't quite understand what to do for the last step.

How do I do the last two steps? I don't get what I'm supposed to do.... or how to do it....

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

2 Answers

28,558 Points

First since you need to use the random number generated you actually have to store it in a variable, currently you just generate a number but then do nothing with the result. Then you need to pull an item/character out of the iterable you get using the random number as the index. You can do this by using square bracket notation which you should have learned in an earlier part of this course.

As a reminder when using bracket notation to pull out items you just place brackets after the variable name and then the index you want to pull out. So to pull out the first item you would use iterable[0] for example.

Darn, you type faster than me XD

Or is it that you spotted this question first?

Alejandro Byrne
Alejandro Byrne
2,562 Points

Thanks, it worked! Yeah, I kinda thought I would have to store it and then do something, got a little confused. Thanks for the help too, Alex.

Don't give up! You are doing very well. You already got a random index all set up!

You just have to use that index to get the item in the iterable. :smile:

Here's how to get a specific character from a string using an index:

"Treehouse"[2]  # Returns "e"

I would recommend to try to do this challenge on your own, but if you keep failing I'd be happy to help more :smile:

Good luck! I hope this helps out. ~Alex