In Python, variables are not just a "box" where we store data. In C or C++, a variable is a memory location. When we change the value, we overwrite what is inside that specific "box". In Python, variables are just tags (pointers) stuck onto an object. And everything in Python is object, as I mentioned in last post. How it works? Imagine a balloon floating in a room as an object. A variable is simply a string tied to that balloon. 1. a = [1, 2, 3] -> We create a balloon and tie a string labeled "a" to it. 2. b = a -> We don’t create a new balloon. We just tie a second string labeled "b" to the exact same balloon. 3. a.append(4) -> We changed the balloon. Since "b" is tied to the same balloon, b now also "sees" the change. Why does it matter? This is where Reference Counting gets its name. Python doesn't count how many "boxes" you have. It counts how many strings are currently tied to the balloon. -> Tie a string? Refcount +1 -> Untie a string (del a)? Refcount -1 Being careful while passing variables(objects) inside functions in python is necessary for this reason. I am trying to learn Python Internals in detail and will share my learnings. Do follow along and tell your experiences. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
Onkar Lapate’s Post
More Relevant Posts
-
🐍 PYTHON QUIZ: Can you guess the output? Most developers get this wrong on their first try. Look closely at the function and the three calls below: What does the console show? 👇 Drop your guess (A, B, or C) before clicking "see more"! . . . . . . . . ✅ THE ANSWER: Option B Wait, what? Why isn't it A? 🧐 In Python, default arguments are evaluated ONLY ONCE at the time the function is defined. Because a list is "mutable" (changeable), Python creates that specific list object once and keeps reusing it for every call. It doesn't create a fresh list each time you run the function! 🛠️ THE FIX: To avoid this "ghost data" bug, always use None as the default: def add_to_cart(item, cart=None): if cart is None: cart = [] cart.append(item) return cart Did this catch you off guard, or are you a Python pro? Let's discuss in the comments! 👇 #Python #CodingTips #SoftwareEngineering #PythonProgramming #ProgrammingQuiz
To view or add a comment, sign in
-
-
🧠 Python Concept That Feels Like a Secret: Function Annotations They look useless at first… but they’re powerful. 🤔 What Are Function Annotations? They let you describe what a function expects and returns. 🧪 Example def add(a: int, b: int) -> int: return a + b Python does NOT enforce this ❌ But tools, editors, and humans LOVE it ✅ 🧒 Simple Explanation It’s like putting labels on boxes 📦 💻 Python won’t stop you from putting toys inside… 💻 but others instantly understand what belongs there. 💡 Why This Matters ✔ Better readability ✔ Helps IDEs catch mistakes ✔ Essential for large codebases ✔ Used heavily in FastAPI, modern Python ⚡ Bonus (Annotations are just data!) print(add.__annotations__) Output: {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>} 💫 Python lets you write code that explains itself. 💫 Function annotations don’t change execution… 💫 but they change how professionally your code reads 🐍✨ #Python #PythonTips #Programming #SoftwareDevelopment #CleanCode #LearnPython #DeveloperLife #DailyCoding #TechCareers #100DaysOfCode
To view or add a comment, sign in
-
-
How does len() function knows how to handle a List, a String, and a Dictionary all the same way in Python? TL;DR: Python Protocols A Protocol is just the set of rules (special methods) an object follows. "Duck Typing" Contract In Python does not care about what the object is, it cares only about what it does. These are represented as dunders (__method__) in Python. 3 Protocols we use everyday in Python: -> Sized (__len__): Tells Python that object has a size. (Powers len()) -> Container (__contains__): Tells Python how to check if something is "inside" the object. (Powers the in keyword) -> Iterable (__iter__): Tells Python that object can be looped over. (Powers for x in obj) Why is this useful? As a developer, we want our code to be intuitive. By following these protocols, we make our custom objects compatible with all of Python’s built-in tools. Protocols are the API of the Python language itself. Using them make custom objects start feeling like native Python parts. I’m deep-diving into the Python protocols this week and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
Why creating a tuple is faster than creating a list in Python? TL;DR: Python doesn’t always create new objects, it uses cached ones! Creating an object is expensive, it needs to ask the OS for memory. To avoid this, CPython implementation uses FREE LISTS for immutable objects like Tuples. How does it work? 1. When you stop using a small tuple (up to 20 elements), Python doesn't delete it from RAM. 2. It moves it to a "Free List" (a specialised cache). 3. When you need a new tuple of that same size, Python just grabs an old one from the cache and renews it. Lists, however, are rarely recycled this way because of their dynamic nature makes them too complex to keep in a simple cache. Why this matters? -> In a a real-time game engine, or a data processing pipeline, you might be creating objects millions of times per second. -> The List Tax: Every time you use [a, b], you are potentially triggering a memory allocation request. -> The Tuple Win: Every time you use (a, b), you are likely just grabbing a "pre-warmed" slot from Python’s internal cache. I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
There is a one line trick to save about 50% RAM usage in Python. By default, Python objects are flexible but heavy. To have flexibility to store any attribute inside objects, every Python object carries a dictionary called __dict__. Each attribute of the object is mapped inside this underlying dictionary. This is why we can add new attributes to an object on the fly: user.new_attribute = "surprise!" That means building a backend system that creates millions of objects (users, transactions, events) will create millions of dictionaries too. But dictionaries are memory consuming because they use hash tables to stay fast. Solution: __slots__ If you know exactly which attributes your object will have, you can tell Python: reserve space just for these fields only. Impact - Memory: SlotsUser uses significantly less RAM (40% to 60%) Speed: Attribute access is slightly faster Strictness: You can’t add random attributes anymore Takeaway - When you don’t need that flexibility, __slots__ helps you keep things lean. I am trying to learn Python Internals in detail and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Python for Beginners – Post #9: Understanding Data Types (Visually!) If you’re starting with Python, data types are one of the first building blocks you must get comfortable with. Here’s a simple visual guide covering: 🔢 Numeric Types – int, float, complex ✅ Booleans – True & False (Yes, they behave like 1 and 0!) ⭕ None Type – When a variable has no value 📦 Collections – list, tuple, set 🔁 range() Function – Generating number sequences efficiently Understanding these helps you: ✔ Write cleaner code ✔ Avoid type-related errors ✔ Think more logically while solving problems If you're learning Python, save this post — you’ll revisit these concepts again and again. 📌 Follow for more beginner-friendly Python content 💬 Comment “PYTHON” if you want the next topic to be Strings or Loops #Python #PythonForBeginners #CodingJourney #LearnToCode #ProgrammingBasics #DataTypes #TechSkills #DeveloperLife
To view or add a comment, sign in
-
-
Day 36 – Hash Tables in Python (What’s really behind dict) 🐍 Today, we’re starting with Hash Tables — the idea behind one of Python’s most-used tools: the dict. If you’ve ever written: user = {"name": "John", "age": 25} then you’ve already used a hash table (even if you didn’t realize it). So why start here? Because hash tables help us store and retrieve data fast. Instead of looping through a list item by item, we can jump straight to what we need. That’s why they show up everywhere: user profiles settings and configurations caching quick lookups in real applications Why Python? Python makes this concept very approachable. Dictionaries look simple on the surface, but there’s a lot of smart engineering underneath. Once you understand how they work, you stop writing “just working” code and start writing efficient, intentional code. And yes — this matters for full-stack development too: Backends use hash tables to manage users, sessions, and data Frontends rely on key-value structures for state and UI logic Performance often comes down to how well you organize and access data We’re starting here because this is foundational. When this clicks, many other data structures and algorithms start to make sense. More coming from tomorrow — challenges, breakdowns, and practical thinking. 🚀 #Day36 #Python #DataStructures #HashTables #SoftwareEngineering #FullStackDevelopment #LearningInPublic
To view or add a comment, sign in
-
Tuples in Python: Immutable (cannot be changed after creation), ordered collection that allows duplicate elements. Syntax:() Two methods: Index(),count() Python 3.14.0 (tags/v3.14.0:ebf955d, Oct 7 2025, 10:15:03) [MSC v.1944 64 bit (AMD64)] on win32 Enter "help" below or click "Help" above for more information. >>> #tuples() >>> a=(4,5.7,"python",4+9j,True,False) >>> print(a) (4, 5.7, 'python', (4+9j), True, False) >>> type(a) <class 'tuple'> >>> len(a) 6 >>> a.count("python") 1 >>> a.index(True) 4 Pooja Chinthakayala Mam,Saketh Kallepu Sir,Uppugundla Sairam Sir
To view or add a comment, sign in
-
Stop wasting RAM! Use Python Generators for Memory Efficiency Are you still using Lists for processing large datasets? If yes, you might be hitting a MemoryError sooner than you think. In Python, Lists are "greedy." They load every single element into your RAM simultaneously. This is fine for small data, but a disaster for millions of records. The Solution: Python Generators Generators use "Lazy Evaluation." Instead of storing the entire dataset in memory, they yield one item at a time, only when requested. The Massive Difference: Imagine you need to process 10 million integers: Python List: Consumes approx. 80 MB of RAM. Python Generator: Consumes only about 100 Bytes. Yes, you read that right—Bytes, not Megabytes! Why you should switch to Generators: Low Memory Footprint: Scale your scripts without crashing your system. Improved Performance: Start processing the first item immediately without waiting for the entire list to be created. Clean Code: Use the yield keyword to handle complex data streams efficiently. Pro Tip: If you only need to iterate over your data once, ditch the square brackets [] and use parentheses () for a Generator Expression. It’s a one-character change that can save your production server! How do you optimize your Python code for scale? Let’s discuss in the comments! 👇 #Python #SoftwareEngineering #DataScience #CodingTips #BackendDevelopment #PythonDeveloper #Optimization #MemoryManagement #CleanCode
To view or add a comment, sign in
-
-
🐍 Ever wondered how Python actually works behind the scenes? We write Python like this: print("Hello World") And it just… works 🤯 But there’s a LOT happening in the background. Let me break it down simply 👇 🧠 Step 1: Python compiles your code Your .py file is NOT run directly. Python first converts it into: ➡️ Bytecode (.pyc) This is a low-level instruction format, not machine code yet. ⚙️ Step 2: Python Virtual Machine (PVM) The bytecode is executed by the PVM. Think of PVM as: 👉 Python’s engine that runs your code line by line This is why Python is called: 🟡 An interpreted language (with a twist) 🧩 Step 3: Memory & objects Everything in Python is an object. • Integers • Strings • Functions • Even classes Variables don’t store values. They store references 🔗 That’s why: a = b = 10 points to the SAME object. ⚠️ Step 4: Global Interpreter Lock (GIL) Only ONE thread executes Python bytecode at a time 😐 ✔ Simple memory management ❌ Limits CPU-bound multithreading That’s why: • Python shines in I/O • Struggles with heavy CPU tasks 💡 Why this matters Understanding this helped me: ✨ Debug performance issues ✨ Choose multiprocessing over threads ✨ Write better, scalable backend code Python feels simple on the surface. But it’s doing serious work underneath. Once you know this, Python stops feeling “magic” and starts feeling **powerful** 🚀 #Python #BackendDevelopment #SoftwareEngineering #HowItWorks #DeveloperLearning #ProgrammingConcepts #TechExplained
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development