Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
Now Reading
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
Understanding the concepts of mutability and immutability, specifically within the context of Mutable and Immutable in Python, is critical in the world of Python programming. These terms refer to how objects behave when they are modified. The ability or inability of an object to be changed in place has significant implications for programming efficiency and data integrity. In this article, we'll delve into the fascinating world of mutable and immutable objects, investigating their properties, use cases, and impact on Python code. Whether you're a new or experienced developer, understanding these concepts will help you write more efficient and robust Python programs.
Objects are categorized as Mutable and Immutable in Python based on whether their values can be changed after creation. Mutable objects can be modified in place, while immutable objects cannot be altered once they are created. Understanding the distinction between these two types of objects is essential for writing efficient and bug-free code.
This article introduces Mutable and Immutable in Python objects, showcases their behaviors through examples, and discusses their impact on memory management and data integrity. Whether you're a novice programmer or a seasoned developer, grasping the concepts enhances your proficiency in Python programming.
Mutable objects in Python are those whose values can be changed after they are created. This means that you can modify the content of a mutable object without creating a new object. Changes made to a mutable object are reflected in place, and any variable referencing that object will see the modifications. Mutable objects play a significant role in data manipulation and are widely used in various programming scenarios.
One of the most common examples of mutable objects in Python is a list. Lists allow you to add, remove, or modify elements without the need to create a new list. Here's an illustration:
Output:
As you can see, the code changes the second element (index 1) of the list from 2 to 99, resulting in the modified list '[1, 99, 3]'.
Dictionaries are another example of mutable objects. You can add, update, or remove key-value pairs without creating a new dictionary:
Output:
As you can see, the code changes the value associated with the "age" key from 30 to 31, resulting in the updated dictionary.
Sets are also mutable objects that allow you to add or remove elements:
Output:
This creates a set containing the elements 1, 2, and 3, and then adds the element 4 to the set, resulting in the updated set '{1, 2, 3, 4}'.
When you create your own classes, you can design them to be mutable. This means you can define methods that modify the internal attributes of instances of your class.
In this case, the Person class's age attribute is mutable. You can modify it directly, which demonstrates the mutable behaviour of custom objects.
Output:
Here, you create a 'Person' instance with the name "Bob" and age 25. Then, you modify the age attribute of the 'person' object from 25 to 26, resulting in the modified age value being printed.
Immutable data types in Python are those whose values cannot be changed after they are created. Once an immutable object is created, its content remains fixed throughout its lifetime. Any attempt to modify an immutable object will result in the creation of a new object with the modified value. Immutable objects play a significant role in ensuring data integrity and are widely used for scenarios where the value should not be altered.
Strings
Strings are perhaps the most common example of immutable in Python. Once a string is created, its characters cannot be changed individually:
Output:
In this, you start with the string "Hello" stored in the 'my_string' variable. When you concatenate it with " World", you create a new string "Hello World", which is stored in the 'new_string' variable. The original string in 'my_string' remains unchanged.
Tuples
Tuples are another example of immutable data types. Once a tuple is created, its elements cannot be modified:
Output:
Here, you start with the tuple '(1, 2, 3)' stored in the 'my_tuple' variable. When you concatenate it with '(4,)', you create a new tuple '(1, 2, 3, 4)', which is stored in the 'new_tuple' variable. The original tuple in 'my_tuple' remains unchanged because tuples are immutable in Python.
Numbers
Numbers, including integers, floats, and complex numbers, are also immutable:
Output:
Here, you start with the integer '5' stored in the 'my_int' variable. When you add '1' to it, you create a new integer '6', which is stored in the 'new_int' variable. The original integer in 'my_int' remains unchanged because integers are immutable in Python.
Frozen Sets
Frozen sets are sets that are also immutable:
Output:
Are Lists Mutable or Immutable in Python?
Lists are mutable objects in Python. This means that you can modify the contents of a list after it's created without creating a new list. This mutability makes lists a versatile and powerful data structure for various programming tasks.
Modifying Lists In-Place
Let's explore how lists' mutability works with some examples:
Output:
In this example, the second element of the list is modified from 2 to 99 using indexing. The change is directly reflected in the original list, showcasing its mutability.
Adding and Removing Elements
Lists' mutability allows for dynamic changes, including adding and removing elements:
Output:
Here:
1. 'my_list.append(5)' adds the element 5 to the end of the list, resulting in '[1, 99, 3, 4, 5]'.
2. 'my_list.remove(3)' removes the first occurrence of the element 3 from the list, resulting in '[1, 99, 4, 5]'.
The append() method adds an element to the end of the list, while the remove() method removes the specified value from the list.
Extending Lists
You can also extend a list by adding elements from another iterable:
The extend() method modifies the list by adding elements from the given iterable.
Output:
In this, 'my_list.extend(extension)' adds the elements from the 'extension' list (which is '[6, 7, 8]') to the end of 'my_list', resulting in '[1, 99, 4, 5, 6, 7, 8]'.
Reordering Elements
Lists can be reordered using methods like sort() and reverse():
Both the sort() and reverse() methods modify the list in place.
Output:
Here:
1. 'my_list.sort()' sorts the elements of 'my_list' in ascending order.
2. 'my_list.reverse()' reverses the order of elements in 'my_list', resulting in the reversed list '[99, 8, 7, 6, 5, 4, 1]'.
In Python, immutable objects are those whose values cannot be changed after they are created. Once an immutable object is instantiated, its content remains constant throughout its lifetime. This characteristic has significant implications for data integrity and program behavior. Let's explore the concept of immutable objects with illustrative examples.
1. Strings
Strings are perhaps the most straightforward example of immutable objects. Once a string is created, you cannot modify its characters directly.
In this example, concatenating " World" to ‘my_string’ creates a new string ‘new_string’, leaving the original string unaltered.
2. Tuples
Tuples are ordered collections that cannot be modified after creation. You cannot change, add, or remove elements from a tuple directly.
Concatenating a new element to ‘my_tuple’ creates a new tuple ‘new_tuple’, preserving the immutability of the original tuple.
3. Numbers
Numeric types like integers and floats are immutable. Any operation that appears to modify a number actually creates a new number.
Here, adding 1 to ‘my_int’ produces a new integer, ‘new_int’, while ‘my_int’ remains unchanged.
4. Frozen Sets
Frozen sets are sets that cannot be modified after creation. They're essentially immutable sets.
Difference Between Mutable and Immutable in Python in Tabular Form
Aspect | Mutable Objects | Immutable Objects |
Definition | Objects whose values can be changed | Objects whose values cannot be changed |
Example | Lists, dictionaries, sets | Numbers (int, float), strings, tuples |
Modification in Place | Can be modified in place using methods | Cannot be modified; create a new object with changes |
Memory efficiency | May consume more memory due to changes | Typically memory-efficient as new objects aren't created for changes |
Hashable | Not hashable (cannot be used as keys in dictionaries or elements in sets) | Hashable (can be used as keys in dictionaries and elements in sets) |
Examples | my_list = [1, 2, 3]<br>my_list.append(4) | my_string = "hello"<br>my_string.upper() |
Use cases | Suitable for dynamic data where values need to change frequently | Suitable for data that should remain constant; useful for keys in dictionaries and hash-based data structures |
Performance impact | May have a performance impact in scenarios involving large-scale data manipulation | Generally has less impact on performance due to immutability |
Assignment | Assigning a mutable object to a new variable creates a reference to the same object | Assigning an immutable object to a new variable creates a new independent object |
Common methods | append(), extend(), pop(), remove() | upper(), lower(), replace(), join() |
The Python ‘id()’ Function
Python's 'id()' function provides a unique identifier (memory address) for objects, helping you distinguish between shared or distinct objects in memory. This aids in object behavior and memory management. Explore 'id()' with examples.
Basic Usage of 'id()'
Here's the basic syntax of the 'id()' function:
'object': The Python object for which you want to retrieve the identity.
Example: Identity of Different Data Types
In this example, the 'id()' function returns the memory address of the variables 'num', 'word', and 'my_list'.
Output:
The actual memory addresses (represented as '<some_memory_address>') will vary depending on your specific Python environment and system. Each variable will have its own unique memory address.
Comparing Identities
You can use the 'id()' function to compare the identities of different variables:
The 'is' operator checks whether two variables reference the same object. In this case, since integers are immutable and small integers are cached by Python, both 'num1' and 'num2' reference the same object with the value 42.
In Python, small integer objects (typically in the range of -5 to 256) are cached and reused, so when you create two integer variables with the same value within this range, they often refer to the same object in memory. Here's what the output should be:
Both 'num1' and 'num2' will have the same memory address ('<same_memory_address_as_num1>'), and the 'num1 is num2' comparison will return 'True', indicating that they refer to the same object in memory. This behaviour is due to integer caching optimization in Python.
Modifying Objects and Identity
Mutable objects can change their contents, but their identity remains constant:
Here, the identity of ‘my_list’ remains the same even after appending an element. The object itself is modified, but its memory location doesn't change.
You first print the identity (memory address) of the 'my_list' and then append an element before printing its identity again. Here's what the output should be:
The memory addresses ('<some_memory_address>') will depend on your specific Python environment and system. However, the critical point to note is that after appending an element to the list, the identity of 'my_list' remains the same. This is because you are modifying the same list object in memory rather than creating a new list.
Immutability and Identity
Immutable objects always have the same identity because their values cannot change:
Both 'word1' and 'word2' reference the same string object "hello" in memory because strings are immutable.
In Python, string interning is a process where the Python interpreter caches and reuses certain string objects with the same value to save memory. For small string literals like "hello", Python typically interns them, which means that multiple variables containing the same string literal will often refer to the same string object in memory. Here's what the output should be:
Both 'word1' and 'word2' will have the same memory address ('<same_memory_address_as_word1>'), and the 'word1 is word2' comparison will return 'True', indicating that they refer to the same string object in memory. This behaviour is due to string interning optimization in Python. However, please note that this behaviour may not apply to all string objects, especially those created dynamically or with non-literal values.
Using id() for Debugging
The id() function can be helpful for debugging and understanding how objects are created and shared in memory. It allows you to verify whether objects are being reused or duplicated.
The id() function provides a powerful tool for examining object identity and memory behaviour in Python. By using it, you can gain insights into how Python manages memory and references, making it a valuable asset for both beginners and experienced developers.
The concepts of mutability and immutability shape how data is stored, accessed, and manipulated in Python. Understanding the distinctions between mutable and immutable objects enables you to write code that is efficient, predictable, and less likely to exhibit unexpected behaviour. By understanding these fundamental concepts, you will be able to make informed design decisions, write cleaner code, and confidently navigate the complex landscape of Python programming.
1. What are the implications of mutability on memory usage in Python?
Mutable objects may consume more memory due to modifications. Immutable objects, on the other hand, are typically more memory-efficient.
2. Why is the distinction between mutable and immutable objects important in Python?
Understanding the difference between mutable and immutable objects is crucial for data manipulation, memory efficiency, and program behavior. Proper handling of mutable objects is necessary to prevent unintended side effects, while immutable objects provide data consistency and predictability.
3. What are mutable data types in Python?
Mutable data types in Python are data structures that allow you to change their values after creation. This means you can add, remove, or modify elements within these data types.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...