Ad

How Do I Properly Pass An Argument To A Function

- 1 answer

I'm from a C++ background so this problem seems a little absurd to me: Let's suppose I have a function:

def scale(data, factor):
    for val in data:
        val *= factor

This doesn't work as intended, if I pass a list, it changes nothing, but

def scale(data, factor):
    for index, val in enumerate(data):
        data[index] *= factor

and lst = [val * factor for val in lst] works properly. How does Python handle argument passing? How do I know if the actual reference, or alias is passed?

Ad

Answer

In python basic data types are passed by value - for example int, str, bool etc are passed by value

Derived data types like classes, enum, list, dict are passed by reference.

In your example, the problem is how you use the for loop - not the function argument. If you do:

for val in lst:
    val += 1

The values inside lst won't get updated because the val is not the same as lst[0], lst[1] and so on IF val is of the basic data types. So, even here, the val is copied by value.

Second, In your example with enumerate:
But when you loop over the enumerated list, you are using data[index] - which modifies the element in the actual list.

And finally, In your example with the generator:

lst = [val * factor for val in lst] - here the generator loops over every element and creates a new list which is again stored in lst. This is something like a = a + 2 but extended to lists.

Ad
source: stackoverflow.com
Ad