Skip to content Skip to sidebar Skip to footer

Python 3x: Indexerror - Tuple Out Of Range

I am having trouble with this project, which is functional immediately after coding, but then breaks as such in PyCharm: Traceback (most recent call last): line 38, in

Solution 1:

You are generating an index between 1 and the length of the tuple inclusive:

Sponsors[randint(1, len(Sponsors))]

Python indexes start at 0, not 1, and the last permissible index is the length minus 1, so exclusive, not inclusive. This is what causes your IndexError:

>>> Sponsors = "Halfords", "QuikFit", "Castrol", "Shell", "BP", "WD40", "GO Outdoors", "Dunlop", "Michelin", "Mobil 1", "Brembo", "Sparco", "Marlboro", "Esso", "Texaco", "Pirelli", "Gulf", "Blitz", "Motul", "K&N">>> Sponsors[len(Sponsors)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range>>> Sponsors[len(Sponsors) - 1]
'K&N'

You'd have to use Sponsors[random.randrange(len(Sponsors))] instead, or much better, use random.choice(Sponsors):

>>>from random import choice>>>choice(Sponsors)
'WD40'
>>>choice(Sponsors)
'Blitz'

which takes care of the boundaries for you.

Next, there is no need to use exec() or eval() in your code. Create a top level list to hold your teams:

teams = []

and add your dictionaries to that. That way you can just address teams[0] for the first team, etc., rather than generate names like dict1 and dict2.

Post a Comment for "Python 3x: Indexerror - Tuple Out Of Range"