Welcome to the Treehouse Community
Looking to learn something new?
Enzo Cnop5,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.
# EXAMPLE # 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)]
james southFront End Web Development Techdegree Graduate 33,258 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.