Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating and Removing From a Set - Possible or Not?

Tags:

python

I don't have a specific piece of code that I want looked at; however, I do have a question that I can't seem to get a straight, clear answer.

Here's the question: if I have a set, I can iterate over it in a for loop. As I iterate over it can I remove specific numbers using .remove() or do I have to convert my set to a list first? If that is the case, why must I convert it first?

like image 561
Dyland Avatar asked Dec 05 '25 16:12

Dyland


1 Answers

In both cases, you should avoid iterating and removing items from a list or set. It's not a good idea to modify something that you're iterating through as you can get unexpected results. For instance, lets start with a set

numbers_set = {1,2,3,4,5,6}
for num in numbers_set:
    numbers_set.remove(num)
print(numbers_set)

We attempt to iterate through and delete each number but we get this error.

Traceback (most recent call last):
  File ".\test.py", line 2, in <module>
    for num in numbers_set:
RuntimeError: Set changed size during iteration

Now you mentioned "do I have to convert my set to a list first?". Well lets test it out.

numbers_list = [1,2,3,4,5,6]
for num in numbers_list:
    print(num)
    numbers_list.remove(num)
print(numbers_list)

This is the result:

[2, 4, 6]

We would expect the list to be empty but it gave us this result. Whether you're trying to iterate through a list or a set and delete items, its generally not a good idea.

like image 103
nathancy Avatar answered Dec 08 '25 05:12

nathancy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!