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

Can someone give me a somewhat detailed explanation of the code here

import random

def random_item(argument): index = random.randint(1, len(argument)-1) return argument[index]

index = random.randint(1, len(argument)-1) # I understand that we have a random integer being generated, I don't understand that len gives the length of the argument I don't understand the "1," and i do not undestand the -1 I fail to see how that could give the 4th letter. Is the -1 decrementing anything?

2 Answers

I think what is tripping you up is len() starts a count from 1 and index starts a count from 0.

len() returns the length of an object. For example: len('item') would return 4 because there are 4 letters in the string "item".

When you are working with an index the count starts from 0. So the first letter is going to be position 0 not position 1.

Example:

argument = 'item'
argument[0]  
# would be equal to "i". 
# i is the first letter in the string 'item' so it is index position 0
argument[3]  
# would be equal to "m". 
# m is the fourth letter in the string 'item' so it is index position 3. 
random.randint(1, len(argument)-1)

randint will generate a random integer within a range you set. In this case it is a random integer between 1 and the length of 'argument' - 1.

So if argument was the string "item" it would generate a random integer between 1 and 3 (number of letters in "item" = 4, therefore 4 - 1 = 3). Since your function needs to return an index of 'argument' you need need to do len()-1 because index starts from 0 not 1.

argument = 'item'
argument[4]  
# even though there are 4 letters in 'item' this would return an error because there is no index 4. 
# The last letter in this example is [3]

Thanks, this makes sense. I see the point of the exercise now.