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


Steven Ward
Steven Ward
699 Points

random_item why end with [] when no list was created?

Ok so i managed to pass this test through the help of the forum, but i am here to learn.

So in this exercise we created a function named random_item. All good so far. Then we've thrown iterable into this mix. Did i miss when this was discussed? I had to google it. I think i understand it correctly.

iterable is an object able to returns its members one at a time is that correct?

So we've done that in the first line.

Then creating what looks like the iterable sum ?

then the return. What really threw me was the [] did we turn treehouse into a sort of list? Is that why we use [minus] ? This task really threw me off.

Sorry if this seems really stupid, but i just want to know why we do this. It's hard for me to do something without knowing why it is done.


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

def random_item(treehouse):
    minus = random.randint(0, len(treehouse)-1)
    return treehouse[minus]
Nthulane Makgato
Nthulane Makgato
Courses Plus Student 19,602 Points

Which challenge is this task related to? Are you on a python track?

Square brackets"[]" are not just used in lists, they are used in any ordered(the order you put them in is how they will stay) dataset i.e. strings, lists, tuples. Dictionaries and sets are not ordered, if I remember correctly. In this case, "Treehouse" is a string and that's why you can use square brackets"[]".

Let me know if this answers your question.

1 Answer

Steven Parker
Steven Parker
230,230 Points

The brackets index into the iterable.

The argument passed in (which you named treehouse) represents an iterable, which could be a list or a string. Based on the length, this function picks one item at random and returns it. If the argument is a list, indexing will give a single item, and if the argument is a string, indexing will give a single character.