Search code examples
pythonpython-3.xfor-loop

Remove even element in a set program not working (Python)


set = {1,2,3,4,4,4,4,5,6,7,8,9,10}
for element in set:
    if(element %2 == 0):
        set.discard(element)
print(element)
print(set)

When I run this program, this error message pops up:

Traceback (most recent call last):
  File "main.py", line 65, in <module>
    for element in set:
RuntimeError: Set changed size during iteration

I was trying to make a for loop that would remove even elements from the given set, and I was expecting it to remove all the even elements from the set.


Solution

  • You should avoid naming your variables after any python key words like set

    You can avoid using loops, and use a set comprehension to filter the data as follows:

    oldset = {1,2,3,4,4,4,4,5,6,7,8,9,10}
    oldset = {b for b in oldset if b % 2 != 0}
    
    //result: {1, 3, 5, 7, 9}