Iterating Over a List in a Function


#1

This might be an obvious question. When I write the for loop, why do I write " for i in numbers" rather than "for i in n"? The "n" is the name of the original list.

Thank you for your insight.


#2

Hi @bdt9123,

Your total function needs to be able to work with any list of numbers, not only with n.

This is your function header ...

def total(numbers):

When the function is called, and executes, the function parameter, numbers, will represent whatever list is passed to the function during the call. Therefore, in the loop header, numbers should be specified as the list through which the loop should iterate.

If you want to use the function to add up the numbers in n, here's how you can do it ...

print total(n)

Then when the function executes, numbers will represent n.

If, later on, you pass another list to the function, numbers will represent that list, for example ...

scores = [4, 9, 7, 2, 8]
print total(scores)

#3

Hi @appylpye,

So there is a reason for parameter and initial loop header matching (both "numbers")?

Also, what is the verbal translation of +=? Just trying to put that character combination in mathematical terms.

Thanks for your assistance.


#4

Yes. The purpose of that function parameter is to enable a programmer to pass a list to the function for processing. The numbers within the list that is passed to the function will be added up, and the result will get returned. In order for the loop to iterate through the same list that is passed to the function, the variable specified after the term in within the loop header must be the same variable that was specified as the function parameter.

If the parameter is numbers, then the loop header might be ...

   for num in numbers:

After the function definition, the programmer could do this ...

list_a = [7, 3, 2, 4, 1]
list_b = [5, 3, 8, 6]
list_c = [9, 1, 3, 7, 4, 6]
print total(list_a) # within function, numbers represents list_a
print total(list_b) # within function, numbers represents list_b
print total(list_c) # within function, numbers represents list_c

During each execution invoked by a function call, numbers represents whatever list was passed to the function.

+= is an augmented assignment operator. If a programmer does this ...

x = 7 ** 2
x += 1 # augmented assignment

The second statement adds 1 to the value of x and assigns the result to x.

There are other augmented assignment operators, for example, -=, *=, and /=.


#5

Thank You! That was a lot of explanation and I really appreciate your time and effort!!


#6