Variable contains integer. I want to use the integer to remove that specific string in a list but it always gives me IndexError: list index out of range

import math
members = ["DT", "Inar_ass", "LemonJuice", "mr fetus", "maia", "stels!", "that one british kid", "that one emo kid", "that one kid", "that one other kid"]
x = 50
while x == 50:
    pair_1 = random.randrange(1,11)
    pair_2 = random.randrange(1,11)

    print(members[pair_1])
    print("loves")
    while pair_1 == pair_2:
        pair_2 = random.randrange(1,11)
    print(members[pair_2] + """
    
    
    """)
    if (members[pair_2]) != pair_1:
        members.remove(pair_1)
        members.remove(pair_2)```

Well, first off: what has math got to do with this? Should you not be using the random module?

Second: members has only 10 items (indexed from 0 to 9) so the random.randrange(1,11) will, at some random point, return an index number that is outside of the 0 to 9 range of members.

As for the rest of your script, I’m very confused about what it is that you’re trying to do.


Just to add…

It’s ‘best practice’ to not have any so-called magic numbers, so to that end, rather than have a line of code such as random.randrange(0, 10), at the start of the script, assign a couple of variables and use those, like this:

start = 0
stop = 10

random.randrange(start, stop)

Also, it seems that you’re tying to remove items from the members list, which means that you have a dynamic list, which is being reduced in length, so the stop = may need to have some feedback that is based on that situation and as such, maybe use stop = len(members). Note! – This will need to be updated each time the length of the list is altered, which can be looped, which means that you’re going to want to learn how to write code loops.

I get that you’re trying to learn Python and have a little fun at the same time, but your fundamentals need some work if you’re going to move this forward.

2 Likes