# Not understanding certain part of code in this

#1

The code works but i'm not 100% certain on what a certain piece of the code does. To be exact the line of code "result += numbers[i]" I know the operator += and what result are doing there. "numbers" is also the "list" that the function is representing, but why the "[i]". If someone could explain that would be great having a hard time on how to read it.

``````n = [3, 5, 7]

def total(numbers):
result = 0
for i in range(len(numbers)):
result += numbers[i]
return result``````

#2

range() gives you a list of numbers, which so happen to match the indexes of numbers. so then you do `numbers[i]` to get from index to list value

#3

``````n = [3, 5, 7]

def total(numbers):
result = 0
for i in range(len(numbers)):
result += numbers[i]
return result``````

1. It defines a list having three numbers.
`n = [3, 5, 7]`

2. Defines a function named total that takes numbers which is a list.
`def total(numbers):`

3. We define a local variable that will store the summation of items (they're numbers) of list
`result = 0`

4. We're going to iterate over list.
update**
we have two ways of iterating through a list.

`for i in range(len(numbers)):`

5.We will iterate over every item of list using bracket notation and add to the result (this variable we made to store only for summation purpose.
Revision ,How we access items of list?
There

x = [1,2,3,4]

print(x[0]) # It prints 1

`result += numbers[i]`
6. Finally we return the result that stores summation of all items(which are numbers) of list.

`return result`

Hope it helps!

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.