Home > database >  Python: why does adding to a set in a for loop terminate?
Python: why does adding to a set in a for loop terminate?

Time:06-13

I recently came across a odd quirk(?) with iterating through sets and I want to ask if anyone knows why it is the case.

First we have the usual iteration through a list. The following will not terminate, and it seems pretty clear why to me: we will add to the list each time we run it, so when the for loop asks for the next number, there will be a new next number, and it will keep iterating.

mylist = [0]
for num in mylist:
    mylist.append(num 1)
print(mylist)

However, with a similar setup using a set, the for loop terminates and it prints {0, 1}. It is almost as if it iterated through a copy of myset.

myset = {0}
for num in myset:
    myset = myset.union([num 1])
print(myset)

CodePudding user response:

While using myset = myset.union[(num 1)] the compiler is creating a new instance myset which has a difference address than the previous one, so when you loop again in the for loop it still has one element in it ; but once the loop is successfully iterated the value is then assigned to the previous instance.

This type of feature is implemented while doing union to reduce any conflict arising due to change in data while the runtime process.

Whereas in case of mylist.append(num 1) it uses the same instance of mylist and append the value in the same address so for each iteration the value of mylist keep changing. Which could cause you errors though.

  • Related