How Do I Properly Pass An Argument To A Function
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?
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.
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module