Appending issue in a list in Python
Question:
I have a list Ci
. I am performing an operation within a loop and appending the values. But I am not able to obtain the expected output. How do I fix it?
arCi=[]
Ci=[1.0]
for i in range(0,4):
Ci=Ci[0]*i
arCi.append(Ci)
Ci=list(arCi)
print(Ci)
The current output is
[0.0, 0.0, 0.0, 0.0]
The expected output is
[0.0, 1.0, 2.0, 3.0]
Answers:
In the first iteration, when i=0
, you make the first term of Ci
as 0.0
and then you are using 0.0
iteratively which gives the answer as 0.0
.
Ci = []
num = 1.0
for i in range(0,4):
Ci.append(num*i)
print(Ci) #yields correct result
I have a list Ci
. I am performing an operation within a loop and appending the values. But I am not able to obtain the expected output. How do I fix it?
arCi=[]
Ci=[1.0]
for i in range(0,4):
Ci=Ci[0]*i
arCi.append(Ci)
Ci=list(arCi)
print(Ci)
The current output is
[0.0, 0.0, 0.0, 0.0]
The expected output is
[0.0, 1.0, 2.0, 3.0]
In the first iteration, when i=0
, you make the first term of Ci
as 0.0
and then you are using 0.0
iteratively which gives the answer as 0.0
.
Ci = []
num = 1.0
for i in range(0,4):
Ci.append(num*i)
print(Ci) #yields correct result