15/18 Iterating over a list in a function


#1

https://www.codecademy.com/courses/learn-python/lessons/lists-and-functions/exercises/iterating-over-a-list-in-a-function?action=lesson_resume

Hi,

I think have a fundamental misunderstanding of lists and functions.

How does the below function “total” know to use the list “n”? What is connecting “total” and “n”?
Why don’t I need to end my code with “numbers = n”, as below (I know it’s incorrect to do so as a mean to complete the exercise, I’m just not sure why?)



n = [3, 5, 7]

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

n = numbers


#2

We would pass n to the function, whereupon it is copied to the parameter, numbers.

print (total(n))

#3

I see what you mean, thanks a heap!

I had an expectation that the list was already being used in the function but I was incorrect.

Appreciate the speedy response.


#4
def total():
    y = 0
    for x in n:
        y += x
    return y

n = [3, 5, 7]

print (total())    # -> 15

Above we do have to reach to the outer scope to find n since it is not defined in the function singnature or body. Python will let us do this as long as we don’t change n. The downside is that it will only work with the one data structure, n. This is a dedicated function that is not very re-usable beyond adding up the list itself as any data is added, removed or modified.

The lesson treats n as some data structure in the running program, and only when it is passed as an argument to the function, does the program latch onto it. The code is not dedicated to any outside data, does not interact with the outside, and returns a value based on the data passed to it. Much better practice since now we have a re-usable and portable implementation.

def total(n):
    y = 0
    for x in n:
        y += x
    return y

With that one subtle change, our program shadows any global n and the variable becomes bound to local scope. Any change to n will not be reflected in global scope (though I’m going to check on this, to be sure). To this function we can pass any data structure, either as a variable of as a literal. Data structures to consider are list, tuple', 'set', and evenstr` (with a minor tweak).

On shadowing…

>>> def total(n):
    y = 0
    n += [9]
    for x in n:
        y += x
    return y

>>> n = [3, 5, 7]
>>> total(n)
24
>>> n
[3, 5, 7, 9]
>>> 

It is not so obvious in the above, because the local variable has physically latched onto the global data structure. Reference objects such as lists and dictionaries are not copied to the local variable. Only a reference to the global is assigned to the local. Changes at the local level are reflected in the global since that is where the change actually takes place.

Let’s try with a different structure and see if n changes at the global level.

>>> total([1, 3, 5, 7])
25
>>> n
[3, 5, 7, 9]
>>> 

Now we see that the change to n locally did not reflect upon the global.


#5

Very clear, thank you for the examples and then the variation/different structure.


#6

You’re welcome. In your sandbox, play with different structures (not just lists) and get a feel for them. General iteration is pretty common and Python has a lot of tools for this that don’t really get explored in this track course. Save it for when you complete the track to really go whole hog, just so you get the gist material here as a basis. In the meantime ground yourself in algorithms that don’t draw upon built-ins unless asked for. This is Basics, and very important to develop in our own mind.

You can always bookmark a topic and come back later. If it’s closed, just ping one of the moderators (or me) to open the topic so you can post again.


#7

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