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 trialbrandonlind2
7,823 PointsI dont understand the reason for the -1
Can someone explain why I'm supposed to minus one when create a random index value?
import random
# EXAMPLE
# random_item("Treehouse")
# The randomly selected number is 4.
# The return value would be "h"
def random_item(iterable):
randomIndex= random.randint(0, len(iterable))-1
item=iterable[randomIndex]
return item
evgenypanov
1,521 PointsBecause in some cases you will have IndexError. For example word 'Treehouse' has nine letters. Our range starts from 0 and if we have range 0-9, we have 10 items. And if we try get iterable[10], we've got IndexError, because we have only 9 items in iterable.
Nick Osborne
4,612 PointsNick Osborne
4,612 PointsThe randomIndex should be: randomIndex = random.randint(0, len(iterable)-1) There is a chance your randomIndex could be -1. You could put randomIndex = random.randInt(1, len(iterable))-1 instead.