简体   繁体   中英

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 :"))
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.

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 :")))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM