i am trying to make a character statblock randomizer with a specific setup(because i am a nerd) where it basically “rolls a D6” 4 times and removes the lowest number. however when i try and remove the lowest number from the list, sometimes I get a “IndexError: pop index out of range” issue every 20 or so iterations. what am i doing wrong?
JavaScript
x
10
10
1
def stat_dice():
2
four_rolls = []
3
4
for _ in range(1,5):
5
item = random.randint(1,6)
6
four_rolls.append(item)
7
min_num = min(four_rolls)
8
index = four_rolls.index(min_num)
9
four_rolls.pop(four_rolls[index])
10
Advertisement
Answer
.pop()
takes an item index, not the item to be removed. .remove()
takes the item to be removed:
JavaScript
1
12
12
1
import random
2
3
def stat_dice():
4
# list comprehension to generate die values
5
rolls = [random.randint(1,6) for _ in range(4)]
6
print('debug: before removal',rolls)
7
rolls.remove(min(rolls))
8
print('debug: after removal',rolls)
9
return sum(rolls)
10
11
print(stat_dice())
12
Output:
JavaScript
1
4
1
debug: before removal [5, 4, 5, 4]
2
debug: after removal [5, 5, 4]
3
14
4
Note in the example above .pop(4)
would generate an IndexError
because valid indexes are 0-3 for 4-element list. .remove(4)
removes the first 4
found in the list.