New value at every iteration in Python

Question:

I want to get the updated values of sigma1 at every iteration and I have sigma[0] = 0.021. But there is an error. I present the expected output.

sigma = []
for t in range(0, 3): 
    sigma[0] = 0.021
    sigma1 = sigma[t] - 0.001
print(sigma1)

The error is

 in <module>
    sigma[0] = 0.021

IndexError: list assignment index out of range

The expected output is

[0.021, 0.02, 0.019]
Asked By: rajunarlikar123

||

Answers:

Your list is empty at first, so you can’t get 0 index of it.

You probably want to set an initial value for you sigma:

sigma=[0.021]
for t in range(2):
    sigma.append(sigma[t]-0.001)

print(sigma)
Answered By: Amin
sigma=[0.021, 0, 0]
"""
if there are n element in the list
sigma=[0] * 5
sigma[0] = 0.021 

"""

#  iterate over the list from 1st index to 3rd index. 
for elem in range(1,3): # replace 3 with n is n numbers are there.
    # update the list with the previous element minus 0.001

    sigma[elem] = sigma[elem-1] -0.001

print(sigma)
Answered By: shivankgtm
sigma=[0.021]
for t in range(2):
    sigma.append(sigma[t]-0.001)

print(sigma)
Answered By: rishabh11336
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.