python - Why is it not safe to modify sequence being iterated on? -


The sequence to be aligned in the loop is not safe to modify (this is only for temporary sequence types Maybe, like lists) If you need to modify the list that you are repeating (for example, to duplicate selected items), then you have to iterate over the copy slice notation making it particularly convenient Is:

  & gt; & Gt; & Gt; For x in [:]: # Copy a piece of the entire list ... if lane (x)> gt; 6: a.insert (0, x) ... & gt; & Gt; & Gt; Why is it not safe to do  for X in an X  

code> ??

Do not get very technical:

If you are running again Python The sequence changes through a temporary sequence and when it is moving through it, it is not always completely clear what will happen. If you include an element in the sequence, then what will happen next, what will be considered as the "next" element in the sequence? What happens if you delete the next object?

For this reason, when you change it, walking through a temporary sequence leads to unspecified behavior. Anything can happen, depending on exactly how the list is implemented: -)


Comments

Popular posts from this blog

paypal - How to know the URL referrer in PHP? -

oauth - Facebook OAuth2 Logout does not remove fb_ cookie -

wpf - Line breaks and indenting for the XAML of a saved FlowDocument? -