Whether the Python function parameter is by value or by reference

Source: Internet
Author: User

This article is a question of getting started with Python into a function.

The following paragraph is the original Python function for the basic tutorial.

passing parameters by value and passing parameters by reference

All parameters (independent variables) are passed by reference in Python. If you modify the parameters in the function, the original parameters are changed in the function that called the function. For example:

#!/usr/bin/python # writable function Description def changeme (mylist):   "Modify incoming list"   mylist.append ([1,2,3,4]);   Print "Function inside value:", MyList   return # call changeme function mylist = [10,20,30];changeme (mylist);p rint "function outside the value:", MyList

The same reference is used for an object that passes in the function and adds new content at the end. So the output is as follows:

Values in function:  [10, 20, 30, [1, 2, 3, 4]] values outside the function:  [10, 20, 30, [1, 2, 3, 4]]


Well, see here, personally test it yourself, code:

def printme (AGE,STR):    str = ' str changed! '    Print age,str    returnstr = ' ori str ' age = 23printme (age,str) Print str
Output Result:

23°c str Changed!ori STR

Seems to be wrong! Not that the function modifies the value of the parameter, so does the actual parameter change?! Is it not equal to strings and lists, etc.?
experienced people know that in Python, strings, tuples, and numbers are objects that cannot be changed, and List,dict are objects that can be modified .
So, just remember the red text of this sentence, you want to modify the immutable object, actually opened up a new storage space new objects, which is why there is a global scope and local scope of the problem.

Whether the Python function parameter is by value or by reference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.