How would I add something to a number over and over again in Python

Question:

I am trying to add numbers in python. I know that it would be x + 3 when you are adding it, but when I try to do it with the program I am writing, it doesn’t work out how I want it to be!
Here is the code:

x = 0 

list = []

for i in range (1,100):
  y = x + 3 
  list.append(y)
print (list)

and the output we get is :

[3,3,3,3,3,3...]

When I want it to be:

[3,6,9,12,15]

Can someone please tell me what I am doing wrong?

Thanks!

Asked By: user14445326

||

Answers:

You need to assign the result back to x so that it accumulates the values. You keep adding to the original value of x, since x never changes.

x = 0
l = []
for i in range(1, 100):
    x += 3
    l.append(x)

print(l)

BTW, don’t use list as the name of a variable. It’s the name of a Python built-in function.

Answered By: Barmar

x is always 0, so you keep running y = 0 + 3, then adding that to the list

You dont need a y variable at all, you can run this in your loop

x += 3
lst.append(x)

Or, maybe simpler

lst = [3*x for x in range(1, 100)]
Answered By: OneCricketeer

Your not increasing or incrementing the variable x. So after the statement list.append(y), in a new line, add x+=3

Answered By: maverick

You can do this:
you are not updating the x so you keep adding the originalx value. so x have to be updated. but since you have y you can do this.

y = 0
mylist = []
for i in range (1,100):
  y += 3
  mylist.append(y)
print (mylist)

or do this you can just update the x value, then it works.

x = 0
mylist = []
for i in range (1,100):
  y = x + 3
  x += 3 #update the x variable
  mylist.append(y)
print (mylist)

And don’t use list as the name of a variable. It’s the name of a Python built-in function. In python so use another word like mylist or something.

Answered By: ppwater

this will help

x = 0 

lst = []

for i in range (1,100):
    y = x+i*3
    lst.append(y) 
print(list)
Answered By: Suraj Shejal

You don’t need the variable x,

Change the line y=x+3 to y=i*3

In your script you are not redefining the value of x each time so you are doing 0+3 countless times. I is the index of the loop so will increase after each iteration, allowing you to have an increasing value in the list output

Answered By: Edward Drake

You can write it in one line like this:

[x for x in range(1, 100) if x % 3 == 0]

or:

[x*3 for x in range(1, 100)]
Answered By: Tobin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.