×

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python.

Now, let us understand what pointers are

Pointers

Pointers are special variables used to store the addresses of another variable. It is generally used in programming languages such as C and C++. These are very useful but are quite complicated. They are represented using an asterisk ‘*’.

Syntax to declare a pointer in C:

datatype *a1
For Example - int *a1;
		float *b1

The syntax to assign the address of a variable to a pointer is:

datatype a1, *a2;
a2=&a1;
For Example – int a1, *a2;
		  a2=&a1;


Four types of pointers are there in C and C++

  1. Null Pointers
  2. Void Pointer
  3. Dangling pointers
  4. Wild pointers

Pointers in Python

Python does not support pointers.

Keeping python user-friendly has been the main idea behind its development. Python has provided several in-built libraries just to ease the work of users. Adding pointers in python would add to the complexities, which would go against the idea of python development.  Thus, pointers are not supported in python.

Although python does not support pointers explicitly, still, users can get the benefits of pointers in python. There are various ways to put on pointers in python.

We will see two of them here:

  1. Usage of mutable types as pointers
  2. Usage of Python custom objects

By the Usage of mutable types as pointers

void add_one(int *a) {
    *a += 1;
}

In the above snippet of C language, the code receives a pointer to an integer(*a) and then increases the value by 1.

The below code shows the main function to carry out the add_one function operation on an integer.

Pointers in Python

Explanation: In the above code, value = 7654 has been assigned to y, and that value is printed first. Further, this value is incremented by one, and the modified value is printed.

Output:

Pointers in Python

Explanation: Foremost y contains an unmodified value and the second y contains the modified value.

Now, let’s try to achieve the same in python.

Pointers in Python

Explanation: In the above code, a mutable list has been used to do the increment.

In this case, the add_one(x) function accesses the unmodified value i.e., 2337, and increments its value by one.  Finally, we get a modified value at last.

Thus, we have achieved our desired task without using pointers, as in C.

The modification was possible because of the use of the list, which is of mutable data type.

Pointers in Python

This figure shows the output of the above python code.

Explanation: Here,the first line contains the unmodified value, and the second line contains the modified values.

Pointers in Python

Explanation - In the above example, we have used the dictionary named counter, which keeps a record of the overall quantity of function calls. When the function named foo() is called, the counter value increases by 2 because the dictionary is a mutable data type.

Pointers in Python

Explanation: it shows the output of the python code written above.

By the usage of Python custom objects

The dictionary option is a great way to compete with pointers in Python, but sometimes it gets monotonous to recall the key name used. If the dictionary has been used in various parts of the application it gets even more difficult. We can use a custom class instead of a dictionary to overcome this issue.

Pointers in Python

Explanation: The above code expresses a Metrics class that still uses a dictionary to hold the real data, which is in the _metrics member variable. This will give the changeability needed by the user. It is now needed to be able to access these values.

It can be performed through properties:

Pointers in Python

Explanation: The code here is making use of @property. The @property decorator here allows accessing functions - adding and mountains_pictures_served.

Now, we will create an object that is the instance of the pointer class defined above.

Pointers in Python

Explanation: The code written above shows the creation of an object of the pointer.

Here also, the values are getting incremented.

Two new functions have been used:

  1. adding()
  2. mountains_pics()

These two functions are capable of modifying the values in the metrics dict. Now we have created a class that can be modified just like the pointers get modified.

Here, one can access both of these functions adding() and mountains_pic()  to simulate pointers in Python.

Pointers in Python

Explanation: The above code contains the full code of the Metrics class.


Related Topics

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

4 minutes read.

Dynamic Typing in Python

Many key factors for developing a great programming language include how it manages its memory space. This memory space largely depends on empty memory boxes called variables that one creates...

3 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

Python Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text] Python Set Methods A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets. Methods ...

4 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Difference between For Loop and While Loop in Python

What is the “For” loop? The “For” Loop is a commonly used control structure in programming that allows us to repeat a set of actions multiple times. The “For” loop is...

3 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Python program to print array element present at even position

Python program to print array element present at even position In this program, we'll see a Python program that prints the elements of an array that are in even positions. We...

1 minute read.

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

Python frozenset()

Python frozenset() class The frozenset() class in Python returns a new frozenset object, optionally with elements taken from iterable. Syntax class frozenset([iterable]) Parameter iterable: This parameter represents an iterable object, like list, set, tuple etc. Return This class returns an unchangeable...

1 minute read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Standard Scalar in Python

Python is a vast and open-source language that contains many libraries, modules, and functions. These functions in python are reusable codes where we don’t need to type the whole code...

4 minutes read.