Python Python Basics (2015) Letter Game App Random Item

random number from interable?

i'm lost, i get lost with these challenges and that worries me because i get the course work but i get lost on the challenges.. im not sure what to do here?
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
import random
def random_item(iterable)
    random.randint(len(interable - 0 -= 1)

You've seen how random.choice() works. It gets a random member from an iterable (like a list or a string).

I want you to try and reproduce it yourself.

First, import the random library.

Then create a function named random_item that takes a single argument, an iterable. Then use random.randint() to get a random number between 0 and the length of the iterable, minus one. Return the iterable member that's at your random number's index.

Check the file for an example.

2 Answers

Craig Dennis
Craig Dennis
Treehouse Teacher

I see two problems. The term is iterable as in able to iterate. I see a place where you have misspelled that.

What is happening with the line return(index) What is index there?

I think you want len(iterable) - 1.

Let me know if those hints don't help get you heading in the right direction.

You got this!

import random
def random_item(iterable)
    random.randint(len(iterable) - 1

is what i came up with, im pretty confused here. I dont know how to get the index out of it? I know what a index is and all that, But i have no clue how to get the index out of this

Craig Dennis
Craig Dennis
Treehouse Teacher

Try just returning the result of random.randint

return random.randint(len(iterable) -1)
Jonathan Beard
Jonathan Beard
1,681 Points


import random

my_list = ['1', '2', '3', '4', '5', '6']

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