Why does zip change my lists?
<p>I noticed a (to me) very strange behavior, I don't understand:
I got a list and an numpy array both with binary values and I want to check the true positives (both==1 at the same time).</p>

<pre><code>import numpy as np
a = [0,0,1,1]
b = np.array([1,0,1,0])

for a,b in zip(a,b):
  if a==1 and b==1:
      print "cool"
print a,b
</code></pre>

<p>Now the craziness begins. a and b are not longer a list or a numpy array but an integer and numpy float? How on earth did that happen?
Thanks for your help!</p>

<p><code>zip</code> did not change your list. You lost the initial references to your lists when you assigned the name <code>a</code> and <code>b</code> to the loop variables in:</p>

<pre><code>for a, b in zip(a,b):
#   ^  ^
</code></pre>

<p>A simple fix is to change those names to say, <code>i</code> and <code>j</code>:</p>

<pre><code>for i, j in zip(a,b):
</code></pre>

<p>One thing to bear in mind when using Python is that names are bound to objects, and therefore can be <em>unbound</em> or even <em>rebound</em>. No name is for keeps. Once you change the object a name is referencing like you did, the name starts to reference the new object.</p>

<p>On another note, <code>for</code> loops assign the objects from the iterable to the name(s) provided, similar to a regular assignment, but with repetitions. So the values you get for <code>a</code> and <code>b</code> at the end of the <code>for</code> loop are those of the last assignment done in the last iteration.</p>

<p>Do bear these in mind.</p>

python list python-2.7 list-comprehension