Re: lists and for loops

2011-08-18 Thread Peter Pearson
On Wed, 17 Aug 2011 20:08:23 -0700 (PDT), Emily Anne Moravec wrote: > I want to add 5 to each element of a list by using a for loop. > > Why doesn't this work? > > numbers = [1, 2, 3, 4, 5] > for n in numbers: > n = n + 5 > print numbers Because integers are immutable. You cannot turn 1 into

Re: lists and for loops

2011-08-18 Thread Tim Chase
On 08/18/2011 07:22 AM, Mark Niemczyk wrote: Or, using list comprehension. numbers = [1, 2, 3, 4, 5] numbers = [n + 5 for n in numbers] numbers [6, 7, 8, 9, 10] Or, if you want it in-place: numbers[:] = [n+5 for n in numbers] which makes a difference if you have another reference to numb

Re: lists and for loops

2011-08-18 Thread Mark Niemczyk
Or, using list comprehension. >>> numbers = [1, 2, 3, 4, 5] >>> numbers = [n + 5 for n in numbers] >>> numbers [6, 7, 8, 9, 10] -- http://mail.python.org/mailman/listinfo/python-list

Re: lists and for loops

2011-08-17 Thread alex23
On Aug 18, 1:08 pm, Emily Anne Moravec wrote: > I want to add 5 to each element of a list by using a for loop. > > Why doesn't this work? > > numbers = [1, 2, 3, 4, 5] > for n in numbers: >      n = n + 5 > print numbers As the for loop steps through numbers, it assigns each integer value to the

Re: lists and for loops

2011-08-17 Thread Jack Trades
> > I want to add 5 to each element of a list by using a for loop. > > Why doesn't this work? > > numbers = [1, 2, 3, 4, 5] > for n in numbers: > n = n + 5 > print numbers > > 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.

lists and for loops

2011-08-17 Thread Emily Anne Moravec
I want to add 5 to each element of a list by using a for loop. Why doesn't this work? numbers = [1, 2, 3, 4, 5] for n in numbers: n = n + 5 print numbers -- http://mail.python.org/mailman/listinfo/python-list