DEV Community

Cover image for Do we have pointers in python like other programming !
AbdlrahmanSaber
AbdlrahmanSaber

Posted on

Do we have pointers in python like other programming !

Pointer is important to understand for the way you’re going to create data structures.

I’m going to start with something that is not a pointer and then compare it to something that does use a pointer.

Let’s say that we have two variable num1, num2

num1 = 11, 
num2 = num1

print("Before: ")
print(num1) #11
print(num2) #11

# then let's change num1

num1 = 22

print("\nAfter\n")
print("num1 =", num1) #22
print("num2 =", num2) #11 
Enter fullscreen mode Exit fullscreen mode

If you realized num2 is still the same 11, you’re wondering now why num2 still equals the same number, is it should update to 22 because we update num1!

So when you set num1 = num2, these are not linked forever, you are just initializing, and that is what happens when you’re working with something that is not using a pointer.

Now, let’s compare this to something that does use a pointer.

We’re going to use a dictionary in python, when you have something set equal to a dictionary, it’s a pointer to the dictionary.
Let’s use the same example and see.

dict1 = {
    'value': 11
}

dict2 = dict1

print("Before: ")

print("num1= ", dict1) # {value: 11}
print("num2= ", dict2) # {value: 11}

dict1['value'] = 22

print("\nAfter\n")

print("num1= ", dict1) # {value: 22}
print("num2= ", dict2) # {value: 22}
Enter fullscreen mode Exit fullscreen mode

so when you set dict2 = dict1 , you are literally saying dict2 points to the exact same dictionary in memory as dict1.

There are a couple of other concepts I want to show here.

The first concept is, let’s just say we have another dictionary called dict3

dict3 = {'value': 57}

dict2 = dict3

print (dict2) # {value: 57}
Enter fullscreen mode Exit fullscreen mode

The pointer can be redirected like this also, and this idea of having a pointer point to a new place is a concept that you’ll use in a data structure.

The second concept is, let’s say now we set dict1 = dict2 now all variables (dict1 — dict2 — dict3)
are pointing to {'value':57} so you might ask now, what happens to that dictionary {'value': 22} which is the old value for dict1 before pointing to dict3. is not a way to get that pointer again {'value': 22}? yes no way to get this pointer again, now we should ask what python does to free this memory up?

Good question, python will run a process called garbage collection to remove this.

If you like the post leave a comment and tell me if you’d like to make a series of posts about data structure and how we can use pointers in it.

Let’s connect on LinkedIn

Top comments (0)