简体   繁体   中英

python passing parameter to a function

I am not clear about the concept of passing lists as arguments to functions in python.

I've tried researching on this myself, didn't find adequate resources.

I want to implement a helper function which returns a number of random items from a given list. (in django queryset)

However, the list may contain multiple rows and passing it by value to a function may result in an out of memory state, correct me if I'm wrong.

How then should I pass a list to a function?

In Python, there are names and values. An assignment statement makes a name refer to a value. An assignment never makes a copy, and assignment never changes a value. It only changes what value a name refers to. Passing an argument to a function is like an assignment: now the local name of the argument in the function refers to the value that was passed in, and copies are never made. This mechanism of names referring to values, and assignments changing which value names refer to, is the same for all objects in Python, regardless of their type.

This gets confusing because of mutable and immutable values. If you pass a mutable value (for example, a list) into a function, and change the value, then the caller's names that refer to that value will also see the changed value. If you pass an immutable value into a function (for example, a string or number), then the value cannot be changed by anyone.

Everything in Python is an identifier. For lists, you can think of the evaluation strategy as "call by reference". It is actually named "call by sharing" .

No. Passing a list to a function does not have any impact in terms of memory. Python does not copy the list.

A full explanation of what Ned Batchelder said:

http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM