×

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

How to Convert int to str in Python

How to Convert int to str in Python In the last article, we studied how we convert a variable with string datatype to integer datatype and discussed different data types available...

4 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

How to write a program in python?

How to write a program in python? In python, writing programs is not a big deal. What we need to work on is our logic and some basic rules of this...

4 minutes read.

EDA in Python

The EDA is the exploratory data analysis; the data scientists mainly use the EDA to understand the main features of the data quickly, the variables in python and the relationship...

6 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Return Statement In Python

Python Return Statement The return statement is generally used for the execution ending and returns the value back to the caller. The return statement can return all types of values and...

2 minutes read.

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

Python Arithmetic Operators

An arithmetic operator is a mathematical operator that is used to operate on two operands. Based on the operator used, action is performed on the operands, and output is delivered. Following...

3 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Isreal() Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

How to Create an Array in Python?

How to Create an Array in Python In the previous article, we have discussed how to declare an array in Python. So, let's have a quick revision of that, and then we...

5 minutes read.

Python hex() function

Python hex() function The hex() function in Python  converts the specified number into a hexadecimal value. Syntax hex(x) Parameter x: The parameter represents an Integer value. Return This function Returns hexadecimal string. Example 1 # Python Program explaining # the hex() function print("The...

1 minute read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.