Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think you've misunderstood what an "iterator object" is. A <code>for</code> loop is not an iterator object. For all intents and purposes, a for loop like this:</p> <pre><code>myList = [0, 1, 2, 3, 4] for x in myList: print x </code></pre> <p>does this (but more efficiently and less verbosely):</p> <pre><code>i = 0 while i &lt; len(myList) x = myList[i] print x i += 1 </code></pre> <p>So you see, any changes made to <code>x</code> are lost as soon as the next loop starts, because the value of <code>x</code> is overwritten by the value of the next item in the list. </p> <p>As others have observed, it <em>is</em> possible to alter the value of a list while iterating over it. (But don't change its length! That's where you get into trouble.) One elegant way to do so is as follows:</p> <pre><code>for i, x in enumerate(myList): myList[i] = some_func(x) </code></pre> <p><strong>Update</strong>: It's also important to understand that <em>no copying</em> goes on in a for loop. In the above example, <code>i</code> and <code>x</code> -- like all variables in Python -- are more like <em>pointers</em> in C/C++. As the for loop progresses, <code>obj</code> <em>points</em> at <code>myList[0]</code>, <code>myList[1]</code>, etc, in turn. And like a C/C++ pointer, the properties of the object pointed to are not changed when the pointer is changed. But also like a C pointer, you <em>can</em> directly modify the thing pointed at, because it's <strong>not</strong> a copy. In C, this is done by <em>dereferencing</em> the pointer; in Python, this is done by using a mutable object. That's why <a href="https://stackoverflow.com/a/9414474/577088">NPE</a>'s answer works. If <code>i</code> and <code>x</code> were even shallow copies, it wouldn't be possible to do what he does. </p> <p>The reason you can't directly change <code>int</code>s the way you can change <code>list</code>s (as in NPE's answer), is that <code>int</code>s aren't mutable. Once a <code>5</code> object is created, nothing can change its value. That's why passing around a pointer to <code>5</code> is safe in Python -- no side-effects can occur, because the thing pointed to is immutable. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload