I have the following code and it works most of the time when I run it:
marvel_heroes = ['Wolverine','Spider-Man','Thor','Iron Man','Hulk','Captain America','Deadpool',
'Daredevil','Cyclops','Mr Fantastic','Professor X', 'Doctor Strange','Thing','Black Panther','Black Widow','Hawkeye','Vision','Shang-Chi', 'Ant-Man','Quicksilver','Star Lord',
'Rocket Raccoon','Drax','War Machine','Falcon']
marvel_heroes.append('Captain Marvel')
#print(marvel_heroes)
length = len(marvel_heroes)
print(length)
team = [marvel_heroes[random.randint(0, length)],marvel_heroes[random.randint(0, length)], marvel_heroes[random.randint(0, length)] ]
print('My team is:')
print(team)
print("\n")
Occasionally I get this error though:
Traceback (most recent call last):
File "main.py", line 12, in <module>
team = [marvel_heroes[random.randint(0, length)],marvel_heroes[random.randint(0, length)], marvel_heroes[random.randint(0, length)] ]
IndexError: list index out of range
I don't really understand how it can be out of range when I have bounded it by the length variable, is this some sort of memory overflow issue or maybe a problem with having duplicate values sometimes?
CodePudding user response:
The upper boundary of random.randint
is inclusive, so you'd have to do
random.randint(0, length - 1)
That being said, I'd recommend you use
team = random.sample(marvel_heroes, 3)
CodePudding user response:
The docs on randint()
are clear:
Return a random integer N such that a <= N <= b. Alias for randrange(a, b 1).
Notice this includes the possibility that both a
and b
can be returned. So with a length of 5, randint
can produce 5
, which will be out of bounds for zero indexed lists.random.choices()
or random.sample()
might be better functions for this.
team = random.sample(marvel_heroes, 3)
choices()
will replicate your current behavior, but sample()
will give you a random unique
selection which seem like what you want.
CodePudding user response:
According to the official documentation, randint(a,b)
will return a value x
so that a <= x <= b
is true.
You could go for randrange()
instead to get a <= x < b
instead.