4. Lists + Function exercise argument input


#1

Hi everyone

Not exactly an issue I have but rather a lack of understanding on a small concept.

The example provided for this section (https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/0/4?curriculum_id=4f89dab3d788890003000096) is this:

def count_small(numbers):
    total = 0
    for n in numbers:
        if n < 10:
            total = total + 1
    return total

lost = [4, 8, 15, 16, 23, 42]
small = count_small(lost)
print small

What I cannot understand is that the argument for the count_small function was 'number', yet we were allowed to input the list 'lost' in place of the number argument within the count_small function (when the 'small' variable was created).

This was explained earlier in the course that such a thing was allowed, but I didn't understand why, and I couldn't find that previous explanation's location anyway. Could someone please explain why Python allows this to occur?

Cheers


#2

In the above, numbers is a parameter, as in a placeholder for the value or object passed in as the argument. If we named the list numbers then it would quickly get confusing for a reader. Best practice is to use local variables in one location if they are placeholders for data structures.

Try this experiment and see what happens (let us know)

numbers = [3, 6, 8, 17, 24, 9]

small = count_small(lost)

Did you get 2? That is the case for Python, but would not be the case for JavaScript. That is why I say best practice because habits we form in one language generally follow us when we work in other languages.

Bottom line, it does not matter what we call our global objects. When they are passed to a function, the local variable identifies the exact same object (in global space) and accesses that object by the reference passed to the function.

Eg.

Add this line your code after the total increment:

numbers[numbers.index(n)] *= 2

Add a new print statement at the end of the code,

print lost

and now run the code. See what happens to lost? There is the evidence that data structures are not copied to function parameters, only a reference to the object is given.


#3

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