0

So I have the following code

n = int(input())
arr = map(int, input().split())
numList = list(arr)
topNum = max(numList)
for i in numList:
    if i == topNum:
        del numList[numList.index(i)]
print(numList)

It takes the following input

5
2 3 6 6 5

and the idea is to remove all occurrences of the top number, but I have a bug where it removes the top number only once. I have checked to print the number if it equals the top number, and it printed twice when testing this so I know it has nothing to do with the if statement and the for loop, so it must have something to do with the way I am deleting it? If so why does it only delete once despite being in a for loop. I understand that its meant to only delete the first occurrence but that's why I have the for loop.

Unknownzdx
  • 179
  • 2
  • 14
  • 3
    It's hard to say if this is the only reason for your bug, but you shouldn't modify the structure of an object (like deleting from it) while iterating it. That causes odd behavior, like elements being skipped. – Carcigenicate Sep 29 '20 at 22:09
  • 3
    You should not modify a sequence over which you are iterating. That can lead to unexpected behavior. – jkr Sep 29 '20 at 22:09
  • 4
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) Not a direct dupe, but it explains how to do what you want. – Carcigenicate Sep 29 '20 at 22:10
  • 1
    Some further comments for your learning, you should have a look at the enumerate function and in this case you could use a list comprehension with an if x != topNum check at the end of it – Vince W. Sep 29 '20 at 22:13
  • @Carcigenicate I get it, I know other solutions the problem I just wanted to know the reasoning behind this method failing, I appreciate the help. – Unknownzdx Sep 29 '20 at 22:15
  • @Carcigenicate also I appreciate you giving me the link but this question was for knowing why my method failed rather than the "right" way to solve it. – Unknownzdx Sep 29 '20 at 22:18
  • The "why" is dependent on the specific implementation of list iterators; likely assumptions it's making about the state of the list. Java outright [throws errors](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) if you try to do what you're doing here, which is arguably a good decision. – Carcigenicate Sep 29 '20 at 22:22

1 Answers1

2

You should not modify the list that you're iterating over.

Here is a way to achieve what you are looking for using functional programming methods. Same as in your method you map the input to integers then we use filter to ignore any numbers in the input which are equal to n.

n = int(input())
numbers = list(filter(lambda x: x != n, map(int, input().split())))
print(numbers)
Jack Ashton
  • 156
  • 5