🐍 This Python behavior confused me for a long time. I saw this code: a = 256 b = 256 print(a is b) It printed: True ✅ Then I changed just ONE thing: a = 257 b = 257 print(a is b) Suddenly: False ❌ Same value. Same code. Different result. What’s going on? 🤯 🧠 The reason: Python object caching. Python pre-creates and reuses small integers (usually from -5 to 256). So when you write: a = 10 b = 10 Both variables point to the SAME object in memory. But beyond that range? New objects get created. 💡 The real lesson: ✨ `is` checks identity, not value ✨ `==` checks value equality ✨ Small details matter in backend systems I’ve seen real bugs caused by this misunderstanding. Now I follow one rule: 👉 Use `==` for values 👉 Use `is` only for None, True, False Python feels simple… until you look a little deeper 👀 And that’s where good engineers are made. #Python #BackendDevelopment #SoftwareEngineering #ProgrammingTips #DeveloperLearning #TechExplained
Jegan Sekar’s Post
More Relevant Posts
-
🧠 Python Feature That Makes Attribute Access Clean: operator.attrgetter Think of it as itemgetter for objects 👌 ❌ Common Way users.sort(key=lambda u: u.age) Works… but gets noisy in big codebases 😬 ✅ Pythonic Way from operator import attrgetter users.sort(key=attrgetter("age")) Cleaner. Faster. More readable ✨ 🧒 Simple Explanation Imagine pointing at a toy 🧸 👉 “Sort by age, not the whole toy.” That’s attrgetter. 💡 Why This Is Useful ✔ Cleaner sorting ✔ Faster than lambda ✔ Reads like English ✔ Used in real-world code ⚡ Bonus Trick Get multiple attributes: attrgetter("age", "name")(user) 🐍 Python has tools that remove noise from code. 🐍 attrgetter is one of those features you don’t notice at first… 🐍 until you can’t live without it #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Day 2 of my Python journey🐍 Today I moved from basic syntax to handling user interaction and manipulating data. I applied these new concepts by writing a basic terminal-based calculator script. 🖥️ Here is a straightforward breakdown of the Day 2 concepts from the CodeWithHarry playlist: ⌨️ User Input: Learned to use the built-in input() function to capture data directly from the terminal console. 🔄 Typecasting: Coming from a JavaScript background where types are often coerced automatically, Python is stricter. I learned that inputs are received as strings by default and must be explicitly converted using functions like int() or float() before performing calculations. ✂️ String Slicing & Methods: Explored how Python handles text data, specifically using bracket syntax [start:end] for slicing, which is a clean and efficient way to extract substrings. Progress is steady. 📈 For those working across different languages, do you prefer stricter typing (like Python) or looser typing (like standard JavaScript) for daily tasks? 👇 #Python #LearningInPublic #SoftwareEngineering #FrontendDev #CodeWithHarry
To view or add a comment, sign in
-
-
🧠 Python Concept That Helps Memory Management: weakref Sometimes… you want to reference an object without owning it 🧠💡 🤔 What Is weakref? A weak reference lets you point to an object without preventing it from being garbage collected. In short: 💻 Normal reference → keeps object alive 💻 Weak reference → lets Python delete it when unused 🧪 Example import weakref class User: pass u = User() r = weakref.ref(u) print(r()) # <__main__.User object> del u print(r()) # None 👀 The object is gone when nothing else needs it. 🧒 Simple Explanation Imagine borrowing a toy 🧸 💫 A normal reference = you keep the toy forever 💫 A weak reference = you only remember the toy 💫 If the owner takes it back, your memory disappears too. 💡 Why This Is Useful ✔ Prevents memory leaks ✔ Used in caches & observers ✔ Helps large applications ✔ Advanced Python concept ⚠️ When to Use 🖱️ Caching systems 🖱️ Event listeners 🖱️ Circular references 🖱️ Long-running apps 🐍 Python doesn’t just manage memory for you… 🐍 It gives you tools to manage it intelligently 🐍 weakref is one of those tools you don’t need every day — until you really do. #Python #PythonTips #PythonTricks #Weakref #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
The "Level Up" Stop writing Python like it’s 2010. 🐍 Python is one of the most readable languages in the world, but only if you use it correctly. Writing "working code" is the first step—writing "Pythonic code" is how you stand out as a senior developer. In these flashcards, I’ve broken down 4 common transformations: Swapping: Goodbye temp variables, hello tuple unpacking. Lists: Turning 4 lines of logic into 1 clean list comprehension. Dictionary Safety: Using .get() to prevent your app from crashing on missing keys. Merging: The modern "|" operator for cleaner data handling. The Question: Which one of these was the biggest "lightbulb moment" for you when you first started? Let’s chat in the comments! 👇 #Python #CleanCode #ProgrammingTips #SoftwareDevelopment #CodingLife
To view or add a comment, sign in
-
-
The sorted() vs list.sort() explanation in most Python content is technically correct and practically useless. "sort() modifies in place, sorted() returns a new list" — yes, fine. But that framing makes it sound like a style preference. In a backend service it is not. list.sort() modifies the actual object in memory. Every other piece of code holding a reference to that object now sees changed data. A cache entry you didn't mean to touch. A parameter the caller expected to be unchanged. An audit log that should have preserved insertion order. None of this crashes. It just silently produces wrong output until someone notices. I wrote a longer piece on this because I also wanted to correct something: a lot of Python articles claim CPython drops the GIL mid-sort so other threads can see a partially sorted list. That's only true when you're using a Python lambda as the key. With no key function, the GIL stays held. The mutation after the sort is the problem regardless, but the claim itself is wrong and worth fixing. Link in the comments. #Python #PythonDeveloper #SoftwareEngineering
To view or add a comment, sign in
-
-
Why Python remembers things after a function is done (code screenshot below) db_connector has finished execution. Its stack frame is gone. Yet connect still remembers host and port. That preserved state is a closure — created automatically when an inner function captures outer scope. You don’t “use closures” explicitly. You design around them. Why this matters: • avoids globals • keeps config scoped • cleaner APIs • safer state Closures aren’t a trick. They’re how Python naturally models state + behavior. Once you notice this, patterns such as DB clients, API wrappers, and rate limiters become obvious. #Python #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
Day 4 of Python was a masterclass in decision-making. I stopped writing "scripts" and started writing "logic flows." Here’s what I learned about building a resilient program: 🔹 The Power of the 'If': From simple one-way decisions to complex Nested and Multi-way (elif) structures. It’s not just about "Yes or No"; it’s about mapping out every possible fog in the road. 🔹 Indentation is Architecture: In Python, a few spaces aren't just for clean looks—they are the law. Indentation tells the computer exactly which code belongs to which decision. If your alignment is off, your logic is off. 🔹 The (Try/Except): I learned how to anticipate human error. Instead of letting the program crash when a user enters a string instead of a number, I used try/except to catch the mistake gracefully and keep the engine running. I’m training my brain to remember that = assigns a value, but == asks a question. I am slowly getting there 🙂 Day 5 is moving into the world of Functions and Iterations (Loops). I’m shifting from making decisions to automating repetitive tasks. The pieces are finally starting to click together. #Python #CodingLogic #BuildInPublic #SoftwareDevelopment #TechJourney #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 44 of #100DaysOfCode 📌 Problem: 762 – Prime Number of Set Bits in Binary Representation Today I solved an interesting bit manipulation problem on LeetCode that combines binary representation with prime number logic. 🔎 Problem Summary: Given two integers left and right, count how many numbers in that range have a prime number of set bits (1s) in their binary form. 💡 Key Insight: The maximum number of set bits for numbers ≤ 10⁶ is 20. So we only need to check prime numbers up to 20: {2, 3, 5, 7, 11, 13, 17, 19} For each number, count the set bits using: Python Copy code num.bit_count() ✅ Python Solution: Python Copy code class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: primes = {2, 3, 5, 7, 11, 13, 17, 19} count = 0 for num in range(left, right + 1): if num.bit_count() in primes: count += 1 return count ⏱ Time Complexity: O(n) 🧠 Concepts Used: Bit Manipulation | Prime Numbers | Set Every day I’m getting more comfortable with binary operations and optimization techniques. #LeetCode #Day42 #CodingJourney #Python #ProblemSolving #BitManipulation #100DaysOfCode
To view or add a comment, sign in
-
-
Day 24/100 — Assignment Operators in Python 🐍 Today I explored one of the most underrated fundamentals — assignment operators! They're not just shortcuts. They make your code cleaner, faster to read, and more Pythonic. Here's what I covered: → = — Basic assignment → += — Add and assign → -= — Subtract and assign → *= — Multiply and assign → //= — Floor divide and assign → **= — Power and assign → %= — Modulus and assign The real insight? Instead of writing score = score + 10, just say score += 10. Your future self (and your teammates) will thank you. ✅ Small habits like using shorthand operators are what separate messy code from readable code. 24 days in. Still going strong. 💪 #Python #100DaysOfCode #FullStack #LearnPython #CodingJourney #PythonBeginners #DevLife
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