Skip to content
Advertisement

my diceroller is having issues with removing elements from the list, any suggestions?

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?

def stat_dice():
    four_rolls = []

    for _ in range(1,5):
        item = random.randint(1,6)
        four_rolls.append(item)
    min_num = min(four_rolls)
    index = four_rolls.index(min_num)
    four_rolls.pop(four_rolls[index])

Advertisement

Answer

.pop() takes an item index, not the item to be removed. .remove() takes the item to be removed:

import random

def stat_dice():
    # list comprehension to generate die values
    rolls = [random.randint(1,6) for _ in range(4)]
    print('debug: before removal',rolls)
    rolls.remove(min(rolls))
    print('debug: after removal',rolls)
    return sum(rolls)

print(stat_dice())

Output:

debug: before removal [5, 4, 5, 4]
debug: after removal [5, 5, 4]
14

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement