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

Enzo Cnop
Enzo Cnop
5,157 Points

Why the square brackets?

Can someone break down what each line is doing step-by-step? I'm confused as to why the square brackets are needed in the third line. Finally, if someone could tell me which lesson covers the '(0, len(iterable) -1)' section of code, I would really like to rewatch it.

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

1 Answer

james south
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

the square brackets is for slicing https://docs.python.org/3/library/functions.html?highlight=slice#slice there is a lesson somewhere in the basics courses on slicing. the 0, len....part is just using the randint method per the python docs https://docs.python.org/3/library/random.html#random.randint after importing the random module and defining the function name and parameter, the body of the function essentially reduces to return iterable[some number]. some number is determined by calling randint with 0 and len(iterable)-1, which means select a random integer between 0 and the length of the iterable, -1. this is because in python iterables are 0-indexed, so the first element has index 0, which therefore means the last element has index length-1. so in the word 'bright' the b is index 0 and the t is index 5, which is the length of 6 minus 1. so by restricting our random integer range to 0 and length-1, we know we will get a number that is an index in the iterable. we then slice with this number to get some random element from the iterable.