<div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">I want to add 5 to each element of a list by using a for loop.<br>
<br>
Why doesn't this work?<br>
<br>
numbers = [1, 2, 3, 4, 5]<br>
for n in numbers:<br>
     n = n + 5<br>
print numbers<br>
<br></blockquote><div><br>The n variable in the for loop refers to each value in the list, not the reference to the slot that value is stored in.<br><br>To update the numbers list you would want something like this:<br><br>
numbers = [1, 2, 3, 4, 5]<br>for n in range(len(numbers)):<br>  numbers[n] += 5<br>print numbers<br><br>Alternatively if you didn't need to update the numbers list you could make a new list like this:<br><br>[n+5 for n in numbers]<br>
<br></div></div>-- <br>Jack Trades<a href="http://www.rentageekit.com" target="_blank"></a><br><a href="http://pointlessprogramming.wordpress.com" target="_blank">Pointless Programming Blog</a><br><br>