Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

195
Vistas
Why do I get this many iterations when adding to and removing from a set while iterating over it?

Trying to understand the Python for-loop, I thought this would give the result {1} for one iteration, or just get stuck in an infinite loop, depending on if it does the iteration like in C or other languages. But actually it did neither.

>>> s = {0}
>>> for i in s:
...     s.add(i + 1)
...     s.remove(i)
...
>>> print(s)
{16}

Why does it do 16 iterations? Where does the result {16} come from?

This was using Python 3.8.2. On pypy it makes the expected result {1}.

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

From the python 3 documentation:

Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection:

Iterate over a copy

s = {0}
s2 = s.copy()
for i in s2:
     s.add(i + 1)
     s.remove(i)

which should iterate only 1 time

>>> print(s)
{1}
>>> print(s2)
{0}

Edit: A Possible reason for this iteration is because a set is unordered, causing some kind of stack trace sort of thing. If you do it with a list and not a set, then it will just end, with s = [1] because lists are ordered so the for loop will start with index 0 and then move on to the next index, finding that there isn't one, and exiting the loop.

over 4 years ago · Santiago Trujillo Denunciar

0

I believe this has got something to do with the actual implementation of sets in python. Sets use hash tables for storing their items and so iterating over a set means iterating over the rows of its hash table.

As you iterate and add items to your set, new hashes are being created and appended to the hash table until you reach number 16. At this point, the next number is actually added to the beginning of the hash table and not to the end. And since you already iterated over the first row of the table, the iteration loop ends.

My answer is based on this one of a similar question, it actually shows this exact same example. I really recommend reading it for more detail.

over 4 years ago · Santiago Trujillo Denunciar

0

Python set an unordered collection which do not record element position or order of insertion. There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.

So don't expect your for loop will work in a defined order.

Why does it do 16 iterations?

user2357112 supports Monica already explains the main cause. Here, is another way of thinking.

s = {0}
for i in s:
     s.add(i + 1)
     print(s)
     s.remove(i)
print(s)

When you run this code it gives you output this :

{0, 1}                                                                                                                               
{1, 2}                                                                                                                               
{2, 3}                                                                                                                               
{3, 4}                                                                                                                               
{4, 5}                                                                                                                               
{5, 6}                                                                                                                               
{6, 7}                                                                                                                               
{7, 8}
{8, 9}                                                                                                                               
{9, 10}                                                                                                                              
{10, 11}                                                                                                                             
{11, 12}                                                                                                                             
{12, 13}                                                                                                                             
{13, 14}                                                                                                                             
{14, 15}                                                                                                                             
{16, 15}                                                                                                                             
{16}       

When we access all the elements together like loop or printing the set, there must be a predefined order for it to traverse the whole set. So, in last iteration you will see order is changed like from {i,i+1} to {i+1,i}.

After the last iteration it happened that i+1 is already traversed so loop exit.

Interesting Fact: Use any value less than 16 except 6 and 7 will always gives you result 16.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda