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

How do you do this challenge?

I am looking for the directions, but I am unsure how to proceed. Some help, please?

jonlunsford
jonlunsford
15,480 Points

Here's how I would solve it:

def random_item(data):
        len_of_iter = len(data)  # count the items in the iterable called data
        value = random.randint(0, len_of_iter - 1)  # get a random value from 0 to len_of_iter minus 1
        return data[value]  # return the item at the index equal to value

1 Answer

AJ Salmon
AJ Salmon
5,675 Points

Hiya Matt!

This one can be hard to understand. Here's what the challenge asks you to do:

  1. Import the random library.
  2. Create the function and set the parameter, it will be given one argument: an iterable object.
  3. Generate a random number with random.randint() that can range between 0 and 1 less than the length of the iterable passed to the argument. Hint: you'll need to use len().
  4. Return the item from the iterable that has the same index as the random number.

Hopefully this is enough help, but if you need more, feel free to ask :)