1

I'm having an issue with a small program I made for school. Here is the (simplified) code:

import random

Val=[23,25,27]

Max=0
for I in range(0,3,1):
  if Val[I]>Max:
    Max=Val[I]

NotMax=Val
Num=NotMax.count(Max)

for I in range(0,Num,1):
  NotMax.remove(Max)

if len(NotMax)==0:
  print("test")
else:
  print(random.choice(NotMax))

for J in range(0,3,1):
  if Val[J]%2!=0:
    print(Val[J])

When trying to run it I get an IndexError at line 23 (second to last), during the last iteration of the for loop, saying that the list index is out of range (see screenshot).

However, I cannot understand why this is happening: I've checked everything multiple times, and it still doesn't work.

But things got even stranger: I was able to find out that, if the NotMax list was created "on its own", or from any list other than Val, then the code worked properly. Only when NotMax=Val, things decide to not work anymore.

Another way to get it working (this time with NotMax=Val) is to outright remove the second for loop: however that defeats the purpose of the program itself (I want to have a list without any Max).

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • You already did some good investigations. This is a common mistake. By removing values from `NotMax` you are actually also removing values from `Val`, because they are the same list. – mkrieger1 Mar 17 '22 at 21:21
  • @mkrieger1 Thanks! I've checked the link you sent and that seems to be the cause. I'm very sorry if I didn't know this! Thanks again :) – Lorenzo Diana Mar 17 '22 at 21:25

0 Answers0