
CLASS-XII COMPUTER SCIENCE FUNCTIONS AND RECURSION NOTES MUTABLE AND IMMUTABLE PROPERTIES OF DATA OBJECT : In Python, almost everything is an object. Numbers, strings, functions, classes, modules and even Python compiled code,all are objects. Python treats all variables as references to the object. This means all variables store the memory address of the actual object. This concept is much like “Pointer” in C and C++ programming language. This means the address of the actual object is stored in the Python named variable, not the value itself. Furthermore, immutable and mutable objects or variables are handled differently while working with function arguments. We will discuss them in below section. In the following diagram, variables a, b and name point to their memory locations where the actual value of the object is stored. Immutable Objects or Variables in Python In Python, immutable objects are those whose value cannot be changed in place after assignment or initialization. They allocate new memory whenever their value is changed. Examples of immutable data types or objects or variables in Python are numbers (integers, floats), strings and tuples. In above diagram, the value of variable b is changed from 11 to 8 after its assignment or initialization. b is an integer and it is an immutable variable. Hence, new memory is allocated for it and old is discarded. In other words, you can never overwrite the value of immutable objects. Every time you change the value of an immutable object, a new object is created in result. Old object is discarded and memory is cleaned up by garbage collector automatically for later use. So in first look, this seems inefficient but in practical it is not. This technique is also used in other very popular platforms like Java and .NET. Immutable Object or Variable Example with Explanation in Python x = 10 print("Value of x:", x) print("ID of x before modification 1 x = 10 2 print("Value of x:", x) 3 print("ID of x before modification:", id(x)) 4 5 # add 20 to the value of x 6 x += 20 7 8 print("Value of x:", x) 9 print("ID of x after modification:", id(x)) Result: Value of x: 10 ID of x before modification: 1528383264 Value of x: 20 ID of x after modification: 1528383584 Explanation: • As you can see memory address of x is changed after modification of value of x variable. This is clear that new memory location is allocated after modification of value of variable x Mutable Objects or Variables in Python In Python, list, dictionary and set are examples of mutable data types. Their values can be changed in place after their assignment or creation. When the value of a mutable variable is changed its memory is not reallocated. In the above diagram, individual string objects in the my_list are immutable but my_list itself is mutable. If we add, remove or modify individual string elements in my_list, the my_list variable points to same object. Mutable Object or Variable Example with Explanation in Python my_list = ["apple", "pear"] print("my_list:", my_list) print("ID of x before modification 1 my_list = ["apple", "pear"] 2 3 print("my_list:", my_list) 4 print("ID of x before modification:", id(my_list)) 5 6 # append "banana" to my_list 7 my_list.append("banana") 8 9 print("my_list:", my_list) 10 print("ID of x after modification:", id(my_list)) Result: my_list: ["apple", "pear"] ID of x before modification: 19925552 my_list: ["apple", "pear", "banana"] ID of x after modification: 19925552 Explanation: • As you can see, memory address of variable is not changed after modifying the object my_list • This has been discussed in detail with examples in this article below. Major Concepts of Function Argument Passing in Python Arguments are always passed to functions by reference in Python. The caller and the function code blocks share the same object or variable. When we change the value of a function argument inside the function code block scope, the value of that variable also changes inside the caller code block scope regardless of the name of the argument or variable. This concept behaves differently for both mutable and immutable arguments in Python. In Python, integer, float, string and tuple are immutable objects. list, dict and set fall in the mutable object category. This means the value of integer, float, string or tuple is not changed in the calling block if their value is changed inside the function or method block but the value of list, dict or set object is changed. Consider the mutable and immutable as states of the function arguments in Python. Let’s discuss it in detail with examples in the following section. Python Immutable Function Arguments Python immutable objects, such as numbers, tuple and strings, are also passed by reference like mutable objects, such as list, set and dict. Due to state of immutable (unchangeable) objects if an integer or string value is changed inside the function block then it much behaves like an object copying. A local new duplicate copy of the caller object inside the function block scope is created and manipulated. The caller object will remain unchanged. Therefore, caller block will not notice any changes made inside the function block scope to the immutable object. Let’s take a look at the following example. Python Immutable Function Argument – Example and Explanation def foo1(a): # function block a += 1 print('id of a:', id(a)) # id of y 1 def foo1(a): 2 # function block 3 a += 1 4 print('id of a:', id(a)) # id of y and a are same 5 return a 6 7 # main or caller block 8 x = 10 9 y = foo1(x) 10 11 # value of x is unchanged 12 print('x:', x) 13 14 # value of y is the return value of the function foo1 15 # after adding 1 to argument 'a' which is actual variable 'x' 16 print('y:', y) 17 18 print('id of x:', id(x)) # id of x 19 print('id of y:', id(y)) # id of y, different from x Result: id of a: 1456621360 x: 10 y: 11 id of x: 1456621344 id of y: 1456621360 Explanation: Parameter Passing "call by value" and "call by name" The most common evaluation strategy when passing arguments to a function has been call by value and call by reference: • Call by Value The most common strategy is the call-by-value evaluation, sometimes also called pass-by-value. This strategy is used in C and C++, for example. In call-by-value, the argument expression is evaluated, and the result of this evaluation is bound to the corresponding variable in the function. So, if the expression is a variable, a local copy of its value will be used, i.e. the variable in the caller's scope will be unchanged when the function returns. • Call by Reference In call-by-reference evaluation, which is also known as pass-by-reference, a function gets an implicit reference to the argument, rather than a copy of its value. As a consequence, the function can modify the argument, i.e. the value of the variable in the caller's scope can be changed. The advantage of call-by-reference consists in the advantage of greater time- and space- efficiency, because arguments do not need to be copied. On the other hand this harbors the disadvantage that variables can be "accidentally" changed in a function call. So special care has to be taken to "protect" the values, which shouldn't be changed. Many programming language support call-by-reference, like C or C++, but Perl uses it as default. If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. The object reference is passed to the function parameters. They can't be changed within the function, because they can't be changed at all, i.e. they are immutable. It's different, if we pass mutable arguments. They are also passed by object reference, but they can be changed in place in the function. If we pass a list to a function, we have to consider two cases: Elements of a list can be changed in place, i.e. the list will be changed even in the caller's scope. If a new list is assigned to the name, the old list will not be affected, i.e. the list in the caller's scope will remain untouched. If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. The object reference is First, let's have a look at the integer variables. The parameter inside of the function remains a reference to the arguments variable, as long as the parameter is not changed. As soon as a new value will be assigned to it, Python creates a separate local variable. The caller's variable will not be changed this way: def ref_demo(x): print "x=",x," id=",id(x) x=42 print "x=",x," id=",id(x) In the example above, we used the id() function, which takes an object as a parameter. id(obj) returns the "identity" of the object "obj". This identity, the return value of the function, is an integer which is unique and constant for this object during its lifetime. Two different objects with non-overlapping lifetimes may have the same id() value. If you call the function ref_demo() - like we do in the green block further down - we can check with the id() function what happens to x. We can see that in the main scope, x has the identity 41902552.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages21 Page
-
File Size-