Python, unlike languages like C and C++, doesn’t truly support pointers. However, everything in Python is an object and all variables hold references to the objects.
These references values behave like pointers in a way.
This guide will help you understand how to handle what Python has close to the concept of pointers by focusing on how you can set “pointers” in Python.
Understanding Pointers in Python
Since Python doesn’t really have Pointers, we need to understand what they are in Python’s context. In Python, variables store memory reference of the object or the location at which the object is stored in the memory, rather than the actual object value. These variables or references behave like pointers.
Setting ‘Pointers’ in Python
Considering Python variables as pointers, ‘setting a pointer’ would then mean ‘assigning a variable’. You can set these ‘pointers’ very simply through assignment:
1 |
1 2 |
a = [1, 2, 3] b = a |
1 |
Here, ‘a’ is a list, and ‘b’ is assigned as a pointer to ‘a’. Changes to ‘a’ will reflect in ‘b’ and vice versa because ‘b’ is also pointing to the same memory location as ‘a’.
Using ‘Pointers’ in Python
Here is an example where we demonstrate the use of pointers in Python:
1 2 3 4 5 6 7 |
def prepend(list, str): # Given a list and a string, prepend the string to the list list.insert(0, str) myList = [1, 2, 3, 4] prepend(myList, '0') print(myList) |
This will lead to the following output:
1 |
['0', 1, 2, 3, 4] |
The function prepend is actually changing the list by adding an element at the beginning of the list. The changes made inside the function is reflecting outside the function because the list passed to the function is the same as the one outside.
Full code:
1 2 3 4 5 6 7 8 |
a = [1, 2, 3] b = a def prepend(list, str): list.insert(0, str) myList = [1, 2, 3, 4] prepend(myList, '0') print(myList) |
Conclusion
Although Python doesn’t have traditional pointers like C or C++, you can achieve similar functionality by understanding that Python variables store the memory reference, not the actual object value. This can provide pointer-like behavior, where changes to an object can be reflected in many places throughout your code.