-1

I have started to write code in python for several days. I have some problem, and I don't have idea what is wrong with my code. I guess that this is really basic problem. Here is my code:

import os

arrayData = [] 
wt = []

def getData(inputFile):
    if os.path.isfile(inputFile):
        print("file exist")
        with open(inputFile) as data:
            for line in data:
                arrayData.append(line.strip())
    else:
        print("file",inputFile,"doesn't exist")


def fcfs():
    counter=1
    index=0
    wt[0] = 0
    while counter <= 10000:
        for i in range(1,100):
            print(index, counter)
            wt[i+counter]=int(wt[i+index-1])+int(arrayData[i+index-1])
            index+=1
            counter += 100


getData('input.txt')
fcfs()

and here is the error:

Traceback (most recent call last):
  File "/root/studia/so_project/main.py", line 30, in <module>
    fcfs()
  File "/root/studia/so_project/main.py", line 20, in fcfs
    wt[0] = 0
IndexError: list assignment index out of range

In the file which I'm using are some random numbers, and I want to sort it with some algorithms.

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
  • `wt` is an empty list, so the assignment `wt[0] = ...` results in an `IndexError` because there is no 0-th element to modify. When in doubt when writing Python code try it yourself in the interactive interpreter. Try `w = []` then try `w[0] = 1` or something. To append to a list use `wt.append()`. – Iguananaut Dec 22 '19 at 16:59
  • Some notes on design/style: Variable and function names should generally follow the `lower_case_with_underscores` style. It’s probably a good idea to use functions which take parameters and return values, instead of manipulating a ton of global variables. – AMC Dec 22 '19 at 17:36

1 Answers1

1

To add an item to a list, use append:

wt.append(0)

wt[0] = 0 works only if there is an item at position 0.

zvone
  • 18,045
  • 3
  • 49
  • 77