mccaw10
mccaw10

Reputation: 3

Why am I recieving a 'list index out of range' error in this program?

I am a student relatively new to coding, using Python at GCSE level and I am struggling to see where I am going wrong with this piece of code, used to correct different students marks by an adjustment factor. Why am I getting an error when both lists have the same number of items in them?

wrongMark = [72,75,23,54,48]
adFactor = [1.25,1.1,1.8,1.3,0.9]
newMark = []
examTable = [["Doc","Sarah","Jar-Jar","Jake","Ben"],
             wrongMark,
             adFactor
             ]
#print(examTable)

for item in wrongMark:
    results = item*adFactor[item]
    newMark.append(results)
print(newMark)

Upvotes: 0

Views: 46

Answers (5)

Harish Dhami
Harish Dhami

Reputation: 1086

you need to use index while iterating. You are using value which is 72 for first iteration. That is why it out of range error. Use something like : for idx in range(len(wrongMark)): results = wrongMark[idx]*adFactor[idx] newMark.append(results)

Upvotes: 0

Chiebukar
Chiebukar

Reputation: 93

The error is In the code: results = item*adFactor[item] It is easier to note the error when you imagine the first iteration of your loop to be : result = 72 * adFactor[72] You get an out of index error because the list adFactor doesnt have a 72nd term.

Upvotes: 0

Ethan
Ethan

Reputation: 1373

Inside your for loop put in a line to print(item) You’ll see it is the value in wrongMark, not the index. You probably want

For index in range(len(wrongMark)):

Upvotes: 2

Levkovich Efrat
Levkovich Efrat

Reputation: 111

The problem is at this row:

   results = item*adFactor[item]

For the first iteration of the for loop, you are trying to access the 72th cell in the list adFactor.

That is why you get "list index out of range"

Upvotes: 0

Joao Ponte
Joao Ponte

Reputation: 170

The error is that you are using for item in wrongMark. In the first iteration, the loop will assign item with value 75 and the list adFactor doesn't have 75 items ;)

One way to solve this is just changing the loop to:

for item in range(len(wrongMark)):
    results = wrongMark[item]*adFactor[item]
    newMark.append(results)

Upvotes: 0

Related Questions