Unlocking the Magic of Memory in Python!
Table of contents
Did you know that everything in Python is an object? That’s right! Whether it’s an int
, float
, bool
, or even a complex
number, they’re all strutting around as objects in Python's memory playground.
Memory Matters
Here’s the scoop: when you assign a value to a variable, that value is first created in memory. Think of it like building a cozy little home for your data! Your variable doesn’t hold the value itself; instead, it holds a reference to where that value lives. So when you write a = b - 0
, Python creates the value 0
in memory just once and assigns its address to both a
and b
. If you decide to change a
, a new value pops into memory, and now a
has a new address while b
still points to the original 0
.
But wait, what happens if there are no variables pointing to a memory address? Well, that’s where Python’s garbage collector swoops in! If no references exist, that memory becomes free space—like an empty lot waiting for new construction. And when a new value moves in, it replaces whatever was there before, like renovating a house!
List It Up!
Now let’s talk about lists. In Python, lists are like magical arrays that store references to values instead of the values themselves. So when you update an element in a list, Python creates a new value in memory and updates the list with the reference to this new value. Easy peasy, right?
But here’s where it gets really fun: imagine having a list of lists! When you have a list (let’s call it list1
) containing another list (list3
), and you make a copy of list1
as list2
, something intriguing happens. If you change an element in list3
through list1
, guess what? Those changes are reflected in list2
too! It’s like having a secret passage between two houses—one change, two places affected!
Curious to dive deeper into the enchanting world of Python memory? Stay tuned—this blog will be published soon!
Subscribe to my newsletter
Read articles from Sai directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Sai
Sai
A graduate from a Tier 3 college, I transformed from someone who hated coding to a passionate enthusiast. Join me as I share my journey and insights into coding, DSA, and machine learning!