Practical Examples of Object References
Working with Lists and Object References
Lists are mutable objects in Python, which means that you can modify them directly through object references. Let's see an example:
## Modifying a list through object references
fruits = ['apple', 'banana', 'cherry']
favorite_fruits = fruits
favorite_fruits.append('orange')
print(fruits) ## Output: ['apple', 'banana', 'cherry', 'orange']
print(favorite_fruits) ## Output: ['apple', 'banana', 'cherry', 'orange']
In this example, both fruits
and favorite_fruits
refer to the same list object in memory. When we modify the list through favorite_fruits
, the changes are reflected in the fruits
list as well.
Using Object References in Function Arguments
As mentioned earlier, when you pass an object as an argument to a function, you're actually passing a reference to that object. This can be useful in certain scenarios, such as when you want to modify an object within a function.
## Modifying a list within a function
def add_item(lst, item):
lst.append(item)
my_list = [1, 2, 3]
add_item(my_list, 4)
print(my_list) ## Output: [1, 2, 3, 4]
In this example, the add_item
function modifies the list passed as an argument, and the changes are reflected in the original my_list
object.
Avoiding Unintended Modifications with Shallow and Deep Copying
As we've seen, when you assign one object reference to another, both variables point to the same object in memory. This can lead to unexpected behavior if you're not careful. To avoid this, you can use shallow or deep copying to create independent copies of objects.
import copy
## Shallow copy
original_list = [1, 2, [3, 4]]
new_list = copy.copy(original_list)
new_list[2].append(5)
print(original_list) ## Output: [1, 2, [3, 4, 5]]
print(new_list) ## Output: [1, 2, [3, 4, 5]]
## Deep copy
deep_copy_list = copy.deepcopy(original_list)
deep_copy_list[2].append(6)
print(original_list) ## Output: [1, 2, [3, 4, 5]]
print(deep_copy_list) ## Output: [1, 2, [3, 4, 5, 6]]
By understanding these practical examples, you'll be better equipped to work with object references in your Python projects and avoid common pitfalls.