reem alfouzan
reem alfouzan

Reputation: 59

assign value from user in a list

i'm trying to create a list that contain values taken from the user .. number of elements in the list is also taken form the user but when i try to assign the inputed value to the index of the list im getting an error " list assignment index out of range"

mu1= []
sigma= []
plots = int(input("please enter number of plots : "))

for i in range(1, plots ) :
    mu1[i] = float(input("Enter the mean for the " + str(i) + " plot :"))
    sigma1[i] = float(input("Enter the STD for the " + str(i) + " plot :"))

Upvotes: 1

Views: 46

Answers (3)

Radosław Zwoliński
Radosław Zwoliński

Reputation: 26

Because you've created two empty lists mu1 and sigma. So you can't replace anything because elements with their indexes don't exist yet. You can create lists filled with zeros like this:

plots = int(input("please enter number of plots : "))
mu1 = [0 for _ in range(plots)]
sigma = [0 for _ in range(plots)]


for i in range(1, plots ) :
    mu1[i] = float(input("Enter the mean for the " + str(i) + " plot :"))
    sigma[i] = float(input("Enter the STD for the " + str(i) + " plot :"))

But i think using append() method is better way.

Upvotes: 1

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

Simply append to the list, python is thinking that you're trying to overwrite a value at an index that doesn't exist.

for i in range(1, plots ) :
    mu1.append(float(input("Enter the mean for the " + str(i) + " plot :")))
    sigma1.append(float(input("Enter the STD for the " + str(i) + " plot :")))

Upvotes: 1

Synthaze
Synthaze

Reputation: 6090

mu1= []
sigma= []
plots = int(input("please enter number of plots : "))

for i in range(1, plots ) :
    mu1.append(float(input("Enter the mean for the " + str(i) + " plot :")))
    sigma1.append(float(input("Enter the STD for the " + str(i) + " plot :")))

You need to use append() because the index you call does not exist in the list.

Upvotes: 3

Related Questions