In some simple applications that I have had to write in C / C ++ I have seen the ease with which certain tasks are solved using pointers . Now, more interested in another language: Python, I have noticed the absence of this concept. What is the reason for this absence? Python being a very powerful and used language, then, what concept replaces it? Is it implicit in the types of data, in the assignments, in the instantiation of a class?
An extremely simple example would be that in C we can encode things like this:
#include <stdio.h>
int main(void) {
// your code goes here
int a = 5;
int *b = &a;
printf("a = %d; b = %d\n", a, *b); // (1)
a = 6;
printf("a = %d; b = %d\n", a, *b); // (2)
return 0;
}
(1): a = 5; b = 5
(2): a = 6; b = 6
b
points to the memory address of a
, any modification in a
can be observed when dereferencing b
. Any assignment by indirection *b = <valor>;
will modify a
.
But, in Python:
a = 5
b = a
print "a = {0:d}; b = {1:d}".format(a,b) # (1)
b is a # resultado: True
a = 6
print "a = {0:d}; b = {1:d}".format(a,b) # (2)
b is a # resultado: False
(1): a = 5; b = 5
(2): a = 6; b = 5
At the beginning a
and b
refer to the same object. Then, when a
is modified a new object is created; then, both refer to different objects and different values.
There is no way to do what in C in Python with this type of data, but it is possible to do something similar with mutable data types; however, it is only possible when we make internal modifications of the mutable data, for example: changing the value of an element of a list.
a = [1, 2]
b = a
print b is a # resultado: True
b.append(3)
print b is a # resultado: True
a = [4, 5]
print b is a # resultado: False