Aliasing Cloning
Aliasing Cloning
1. Aliasing:
Aliasing occurs when two or more variables refer to the same object in memory. When you create an
alias, no new object is created, and changes made to one variable will affect the other because they
both reference the same object.
Example of Aliasing
list1 = [1, 2, 3]
list2 = list1 # Alias created; both list1 and list2 point to the same object
In this case, list1 and list2 are aliases—they point to the same list in memory. Any change made to either
list1 or list2 will be reflected in both.
2. Cloning (Copying):
Cloning (or copying) creates a new object that is a copy of the original object. When you clone an object,
changes made to the new object do not affect the original one, as they are stored at different memory
locations.
Shallow Copy: A shallow copy creates a new object, but does not recursively copy the contents of nested
objects. For mutable objects like lists, this means that while the outer object is copied, the inner
elements are still referenced (aliased).
import copy # (The copy module in Python provides functions to create shallow and deep copies of
objects. You can use it to avoid aliasing and create independent copies of mutable objects like lists or
dictionaries.)
The outer list was copied, but the inner list [3, 4] is still shared between list1 and list2.
Deep Copy: A deep copy creates a completely independent copy of the object, including any nested
objects. Changes made to any part of the copied object do not affect the original.
import copy
list2[0] = 99
In Python, the try and except blocks are used for exception handling. They allow you to handle errors or
exceptions that may occur during the execution of your code, preventing the program from crashing.
Here's a breakdown of how they work:
Basic syntax:
try:
except ExceptionType:
How it Works:
try block: Contains the code that might raise an exception. Python will execute this block first.
except block: Contains code that will run if an exception occurs in the try block. You can specify different
types of exceptions to catch specific errors.
try and except to handle runtime errors (e.g., division by zero, invalid input).