↓ Skip to main content
Python

Python: Pointers & Reference

In Python, there are no explicit pointers like in some other programming languages. In python everything is an object and references to objects are stored in variables.

When you assign an object to a variable, the variable stores a reference to the object in memory. This means that changes to the object will be reflected in all variables that reference that object.

Here’s an example that demonstrates how references work in Python:

a = [1, 2, 3]
b = a
b[1] = 4

print(a)
# Output: [1, 4, 3]

In the example above

  1. a is assigned a reference to a list object [1, 2, 3].
  2. Then b is assigned a reference to the same list object as a.

When you change the value of b[1] to 4, the change is reflected in the original list object, which is referenced by a. When you print a, the output is [1, 4, 3], which shows that the change to b also affected a.

This demonstrates that in Python, variables store references to objects, not the objects themselves. When you modify an object, all references to that object will see the changes.

If you want to create a copy of an object that is independent from the original object, you need to use the copy module.

Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Python: Class

·1 min
Learning to write Python code? A Python class is a blueprint for creating objects. It defines a set of attributes and methods that can be used to manipulate those attributes. Here’s an example of a simple Python class:

Python: Decorators

·1 min
Let’s learn about decorators @iamdecorator Decorators are used to modify or extend the behavior of functions and classes. They are useful for wrapping a function or class with additional functionality, such as logging, access control, performance measurement, or adding attributes. This can reduce code duplication, increase readability and maintainability.

Python: Inheritance

·2 mins
Inheritance is a mechanism in object-oriented programming (OOP) that allows you to create new classes that are derived from existing classes. The derived class inherits attributes and behaviors from the base class, and can also have additional attributes and behaviors of its own.