K
K
Kostya Vinogradov2020-09-05 00:05:09
Python
Kostya Vinogradov, 2020-09-05 00:05:09

Why does python ignore the first value of a list?

This is from exercise.

list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

sum = 0
mult = 0
for sum in list:
    if(sum<9):
        mult = mult + list[sum]
        sum = sum+1
    else:
        print(mult)


Should be 45, instead it outputs 44. It's as if python is ignoring list[0], which is 1. What's wrong with the code?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
P
PavelMos, 2020-09-05
@hjolming

for sum in list- this is a search of the elements of the list in order;
mult = mult + list[sum]this is an appeal to the element of the list by index. The first element is 1, which means it will be the second by index, because the numbering starts from zero. - it makes no sense, this value will be reset at the beginning of the loop, because there is a iteration of sum from the list
sum = sum+1

K
Klork, 2020-09-05
@Klork

Try replacing "list[sum]" with "sum"

S
SirotaKazansky, 2020-09-05
@SirotaKazansky

And you don't have list[0] there, your "sum in list" is 1, 2 and so on. That is, sum is not an index.
Run, you will understand what I mean:

list = [123, 277, 783, 8974, 75, 78676, 147, 7828, 9099]
sum = 0
for sum in list:
    print(sum)

S
soremix, 2020-09-05
@SoreMix

Because you are iterating the list, and for some reason you are accessing the index by the sum.

list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

sum = 0
mult = 0
for number in list:
    if (sum<9):
        mult = mult + number
        sum = sum+1
    else:
        print(mult)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question