How to Set a Pointer in Python

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:

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:

This will lead to the following output:

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:

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.