Python functions passing mutable immutable objects

Source: Internet
Author: User

Parameter passing of the Python function:

Immutable types: Values such as C + + are passed, such as integers, strings, and tuples.
such as fun (a), passing only a value, does not affect the A object itself.
For example, in Fun (a) to modify the value of a, just modify another copy of the object, does not affect the a itself.

mutable types: References such as C + + are passed, such as lists, dictionaries.
such as Fun (LA), is the real transfer of LA, the modified fun outside of LA will also be affected

Everything in Python is an object, strictly meaning we can't say value passing or reference passing, we should say immutable objects and pass mutable objects.

Python-Passed immutable object instance:

# !/usr/bin/python3 def  # There is no relationship between a and the next line of a, just represents the value of the function input parameter, is an object is not a variable name    a = ten# here produces a function inside the variable A and assigns the value B = 2changeint (b)print#  result is 2

passing a Mutable object instance

A mutable object modifies a parameter in a function, and the original parameter is changed in the function that calls the function. For example:

#!/usr/bin/python3 #Writable Function DescriptiondefChangeme (mylist):#The mylist here is the list object corresponding to the function input parameter, which can be changed by the value of the column table .   "to modify an incoming list"Mylist.append ([1,2,3,4]) #修改列表里的值   Print("value in function:", MyList)return #Call the Changeme functionMyList = [10,20,30]changeme (mylist)Print("values outside the function:", MyList)

The object that passes in the function and adds new content at the end is the same reference, which is the list object. So the output is as follows:

Value in function:  [10, 20, 30, [1,  2, 3,4]  out-of-function values:  [10 , 20,  30, [1 2, 3 , 4] [       

Python functions passing mutable immutable objects

Related Article

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.