Changing the value of an item in a list in a Python for loop
<p>I have created a function and am passing the function a list of strings like this: 
<code>['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX']</code></p>

<p>I have created a variable X with 26 values; I refer to these values as 'card' in my code below ('for card in X'). </p>

<p>I am using itertools and list comprehensions to create a list of strings so that each value in X is substituted for 'XX' in a new list. </p>

<p>For example: <code>['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX']</code> will expand to <code>['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value1'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value2'] etc</code></p>

<p>I am creating a list of values called tmp and substituting the list of 'X' values (called card) for one of the items in tmp (called 'XX') using a for loop.</p>

<pre><code> unitoffive = list(itertools.combinations(unit,5))
 newunit = [list(line) for line in unitoffive if 'XX' in line]


 tmp = [[line,card] for line in newunit for card in X]
 for line in tmp:
     line[0][4] = line.pop(line.index(line[1]))
     print line

  for line in tmp:
     print line
</code></pre>

<p>My script is exhibiting behavior I cannot understand. When the print line statement in my first for loop is executed I see the modified list that I expect. When the second print line statement is called I see another and incorrect version of my list. I can't return and use tmp since it only seems to contain the correct values within the for loop in which it was modified. </p>

<p>I know that Python lists can be tricky to modify in a for loop and I tried changing my code to loop over <code>for line in tmp[:]</code> but that didn't solve my problem.  </p>

<p>The print line statement in this section of code prints <code>['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value1'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value2'] etc</code> as expected:</p>

<pre><code>for line in tmp:
  line[0][4] = line.pop(line.index(line[1]))
  print line
</code></pre>

<p>The print line statement following it prints <code>['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value26'], ['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'value26'] etc</code></p>
