Ryan Ross
Ryan Ross

Reputation: 139

Adding on to numbers already in a list in python

Ok so I need to add 30 to every individual number in a list:

numbers = [56,3,9,1002,33,66,789,9001,999,222,82,71,5,3]

and print the answer out.

I hear that you can use a for loop to do this, but I can't figure it out.

Any help would be amazing, thank you!

Upvotes: 0

Views: 53

Answers (2)

paxdiablo
paxdiablo

Reputation: 881123

The classical method, changing the actual items in the existing list:

>>> numbers = [56,3,9,1002,33,66,789,9001,999,222,82,71,5,3]

>>> for x in range(len(numbers)):
...    numbers[x] = numbers[x] + 30

>>> print numbers
[86, 33, 39, 1032, 63, 96, 819, 9031, 1029, 252, 112, 101, 35, 33]

The more Pythonic way, though keep in mind this is creating a new list:

>>> numbers = [56,3,9,1002,33,66,789,9001,999,222,82,71,5,3]

>>> numbers = [x + 30 for x in numbers]

>>> print numbers
[86, 33, 39, 1032, 63, 96, 819, 9031, 1029, 252, 112, 101, 35, 33]

Upvotes: 1

Eliezer
Eliezer

Reputation: 767

In general, if your lists contain homogeneous, numeric data, it will be faster to perform computations in numpy. For your particular question, the following would be a very fast and direct solution:

import numpy as np
x = np.array([56,3,9,1002,33,66,789,9001,999,222,82,71,5,3])
print x + 30

Upvotes: 1

Related Questions