Python Variables and Memory Locations

🚨 This behavior of Python might look like a BUG… but it isn’t actually. a = 10 b = 10 print(id(a)) print(id(b)) 👉 Same memory location 😲 “Why do we have two variables pointing to the same memory location?!” Here comes the second one and things get interesting 👇 a = [1, 2, 3] b = a b.append(4) print(a) # [1, 2, 3, 4] 🔥 👉 Hmmm… why did ‘a’ change?! 💡 Explanation: ⭐ id() returns the identity of an object ⭐ Python reuses memory locations for immutable values ⭐ For mutable objects however, there is no copying, just pointers! ⚠️ The misconception: Most people believe ‘=’ copies objects in variables. 👉 Nope! ✅ Solution: b = a.copy() Now the two variables are separate ✅ 🔥 Consequence: It can seriously mess up your program’s logic! Ever got caught by such a ghost bug in Python? 👇 #CodeWithSujith #Python #Programming #Coding #PythonTricks #LearnPython #PythonBeginner #100DaysOfCode #DeveloperJourney

  • No alternative text description for this image

If you studied pointers in C/C++ then it'd be so much easy for you to understand this behavior. The variable 'a' has an address in the memory. When you assigned 'b' to 'a' the reference (address) of the 'a' is stored in 'b'. So, when you append '4' into b, because of 'b' was referring to 'a', the change on 'b' also caused 'a' to change and append the '4' value.

Like
Reply

Thanks for good explaination

Nice one and well explained 🤩👏👏

See more comments

To view or add a comment, sign in

Explore content categories