lists and for loops

E

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
 
A

alex23

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 label n. What n holds is a number, _not_ a reference to the
number in the list. So when you reassign n to hold n+5, you're
pointing n at a new number, not modifying the original number being
referred to.

So what you need is a reference to the position of the number in the
list, so you can reassign the value that's held there. The common
pattern is to use enumerate, which lets you step through a list giving
you both an reference (index) & a value:

numbers = [1, 2, 3, 4, 5]
for i, n in enumerate(numbers):
numbers = n + 5

Here you're reassigning each list element to hold its old value plus
5.

Hope this helps.
 
T

Tim Chase

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 numbers:
numbers = [1,2,3,4,5]
digits = numbers
numbers = [n+5 for n in numbers]
numbers, digits ([6, 7, 8, 9, 10], [1, 2, 3, 4, 5])
numbers = [1,2,3,4,5]
digits = numbers
numbers[:] = [n+5 for n in numbers]
numbers, digits
([6, 7, 8, 9, 10], [6, 7, 8, 9, 10])

-tkc
 
P

Peter Pearson

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 6.
Contrast this behavior with lists, which *are* mutable:
numbers = [[1],[2],[3],[4],[5]]
for n in numbers:
.... n[0]= n[0] + 5
....[[6], [7], [8], [9], [10]]

For practical purposes, I'm sure you'll find other responders'
excellent posts to be of more immediate use, but keeping
mutability in mind helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,416
Latest member
LionelQ387

Latest Threads

Top