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
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
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
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
>
> 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.
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