💬 Today’s Insight: A Hidden Trap in Python (Mutable Default Arguments) Take a look at this function: def tricky(n, lst=[]): if n > 0: lst.append(n) return tricky(n-2, lst) return lst print(tricky(5)) print(tricky(4)) At first glance, everything seems normal… but the output might surprise you 👀 👉 The key issue here is using a mutable default argument ("lst=[]"). In Python, default arguments are evaluated only once when the function is defined, not each time it’s called. This means the same list is reused across multiple function calls. 📌 So what happens? - First call → builds "[5, 3, 1]" - Second call → continues using the SAME list → "[5, 3, 1, 4, 2]" 💣 This leads to unexpected behavior and bugs that are hard to trace. --- ✅ Best Practice Always use "None" as the default value for mutable types: def tricky(n, lst=None): if lst is None: lst = [] if n > 0: lst.append(n) return tricky(n-2, lst) return lst Now each function call gets its own fresh list ✔️ --- 🎯 Takeaway - Avoid using mutable objects as default arguments - Use "None" and initialize inside the function - Small detail… but huge impact on your code quality --- #Python #Programming #DataScience #AI #CodingTips #SoftwareEngineering #LearningJourney
Python Default Argument Gotcha: Avoid Mutable Lists
More Relevant Posts
-
🚀 Day 28 – The 30-Day AI & Analytics Sprint 🐍 Python Discussion: Tuples & Mutability Consider this tuple: Python t = (1, 2, [3, 4]) Here’s the interesting question: ❓ Why does this work? Python t[2].append(5) But this raises an error? Python t[0] = 10 💡 The key idea: Immutability vs Mutability A Tuple in Python is immutable, which means you cannot change the elements it holds after creation. However, the tuple above contains a list, and lists in Python are mutable. ✔ When we run: Python t[2].append(5) We are not changing the tuple itself. We are modifying the list object stored inside the tuple. So the tuple still points to the same list — but the list’s contents changed. Result: Python (1, 2, [3, 4, 5]) ❌ But when we try: Python t[0] = 10 Python blocks it because this would change the reference stored in the tuple, which is not allowed. 🧠 In simple terms: Tuple → Immutable (references cannot change) List → Mutable (content can change) ✨ That’s why: A tuple is immutable, but it can still contain mutable objects. 💬 Discussion: Can you think of a real scenario where storing a mutable object inside a tuple could cause unexpected bugs? #Python #AI #DataScience #Programming #LearningInPublic #Analytics #30DayChallenge #PythonTips #AIAnalyticsSprint
To view or add a comment, sign in
-
Day 5 of the AI & Data Analysis Challenge ✨❤️ سؤال بسيط في Python لكنه مهم لأي حد شغال في Data Analysis. When we use *args in a function, where are the values stored? 📌 Options: 1)Tuple 2)List 3)Set 4)String ✅ Answer: Tuple Explanation: When we use *args in Python, the function can accept a variable number of arguments. Python automatically collects these values into a tuple. Example: Python def numbers(*args): print(type(args)) numbers(1, 2, 3, 4) Output: <class 'tuple'> 💡 Why does Python use a tuple? Immutable (values cannot be changed) Faster than lists Safe for function arguments Did you know this before? 👀 #Python #DataAnalysis #AI #LearningInPublic #DataScience Rawan Mahmoud Mariam Ghareeb
To view or add a comment, sign in
-
-
🚀 Day 9 of My Generative & Agentic AI Journey! Today’s focus was on Dictionaries in Python — a powerful way to store data in key-value pairs. Here’s what I learned: 📘 Dictionaries in Python: • Store data in key:value format • Defined using {} or dict() • Example using dict(): student_name = dict(first_name="Rohan", last_name="Sharma") • Example using {}: student = {} student["first_name"] = "Mohan" ⚙️ Common Dictionary Operations: • del → Used to delete a key-value pair Example: del student["first_name"] • popitem() → Removes the last inserted item Example: student_name.popitem() • update() → Used to update or add new values Example: student.update({"age": 20}) 👉 Key takeaway: Dictionaries are extremely useful for handling structured data and are widely used in real-world applications like APIs and databases. Another step forward in my Python learning journey 🚀 #Day9 #Python #GenerativeAI #AgenticAI #LearningJourney #BuildInPublic
To view or add a comment, sign in
-
In Python, everything is an object. That one fact broke my mental model this week. I'm transitioning from Software engineering to AI engineering. Week 1, Day 7 🗓️ Here's what clicked 😲. Since everything in Python is an object, every object has a unique memory address. Dict uses this to store and find values in O(1). It hashes the key, jumps directly to the slot. No scanning. No searching. But this only works if the key never changes. A mutable key changes its hash, changes its slot, and your value becomes permanently unreachable. Silent corruption 🤯 . So dict keys must be immutable. And immutable means hashable. Hashable objects carry two methods that work as a pair: __hash__() generates the slot number & __eq__() confirms the exact key at that slot. Override one without the other and Python punishes you: ``` class BrokenDog: def __eq__(self, other): return self.name == other.name # forgot __hash__ hash(BrokenDog("Rex")) # ❌ TypeError: unhashable type ``` But Python's built-in types like dict and str already override __eq__() to compare contents and not addresses. That's why two dicts with identical keys and values return True on `==`. One more thing that surprised me. Since every object in Python carries this overhead of creation, hashing, and storage, even a simple `int` is not free. That's exactly why NumPy exists to escape Python's object model and work directly with raw memory for numerical computation. For more details, refer: https://lnkd.in/gZCGFRBB What's the Python concept that surprised you most when you first learned it? #AIEngineering #Python #LearningInPublic #CareerTransition #SoftwareEngineering
To view or add a comment, sign in
-
AI writes Python code... backwards. I noticed something that kept bugging me: AI coding assistants like Claude Code most often generate Python functions in bottom-up order, with helpers first and entry points last. What's the deal? This forces you to read code from the bottom up to understand what it does. The exact opposite of how we naturally read, from the headline to the supporting details, like a newspaper! So I built 🔧 flake8-stepdown, a tool that detects and auto-fixes function ordering violations. It works as a flake8 plugin and as a standalone CLI. I wrote a blog post to explain how it works! 💡 Don't just prompt AI to "write better code", constrain it with deterministic tools (linter, auto-formatter, ...) Links in the comment below 👇 #Python #AI #CodeQuality #DeveloperTools #OpenSource
To view or add a comment, sign in
-
I keep seeing people complain that Python is too slow for real AI work in 2026. It's a weird take. Python didn't take over machine learning by being fast at execution. It won because it's fast to iterate in. It basically acts as the steering wheel for a much faster engine. You mess with the knobs and get an experiment running in minutes instead of days. The actual heavy lifting (the matrix math and model training) runs on C, CUDA, or Rust under the hood. Libraries like PyTorch and JAX handle the hard stuff, and Python just glues it together so you don't have to worry about memory management. This is exactly Meta's playbook. Most of their research and production runs on PyTorch. They build and break things in Python, and only rewrite the critical bottlenecks in C++ when scale demands it. It's the exact same logic as using Django with Rust. Do 95% of your work in the language that gets out of your way, and only pull out the raw power when you actually need it. Especially now that coding agents are heavily optimized for Python, the execution speed argument barely matters. I'd much rather have a stack that lets me test ten ideas in an afternoon. How many of you are still sticking with Python this year?
To view or add a comment, sign in
-
📊 Solved a Probability Problem using Python! Today I worked on a statistics problem involving normal distributions and learned an important concept about combining independent variables. 🔍 Problem Summary: Given two independent normal variables: X ~ N(10, 3) Y ~ N(20, 4) Find the standard deviation of (X + Y). 💡 Key Insight: For independent variables: 👉 Var(X + Y) = Var(X) + Var(Y) So, ✔️ Variance = 3² + 4² = 9 + 16 = 25 ✔️ Standard Deviation = √25 = 5.0 💻 Implemented this logic using Python and verified the result. 📌 Takeaway: Understanding core concepts like variance addition makes solving such problems quick and intuitive — very useful for interviews and real-world data analysis. Continuing to strengthen my foundations in probability, statistics, and problem-solving 🚀 #Python #Statistics #DataScience #MachineLearning #AI #InterviewPreparation #LearningJourney link of #Solution :- https://lnkd.in/ggQa3yz3
To view or add a comment, sign in
-
-
🧠 Day 26 – The 30-Day AI & Analytics Sprint 🌜 🔥 Python Tricky Question! What will be the output of this code? def tricky(n, lst=[]): if n > 0: lst.append(n) return tricky(n-2, lst) return lst print(tricky(5)) print(tricky(4)) ❓ Choose the correct answer: A) [5, 3, 1] [4, 2] B) [5, 3, 1] [5, 3, 1, 4, 2] C) [5, 3, 1] [4, 2, 1] D) Error 💡 Hint: Default arguments in Python are evaluated only once! 👇 Drop your answer before checking the solution! 🚀 Why this matters? This question reveals one of the most common pitfalls in Python: 👉 Using mutable objects as default arguments It can lead to unexpected bugs in real-world applications 😅 #Python #Programming #AI #DataScience #CodingChallenge #30DayChallenge #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Day 5 of My Generative & Agentic AI Journey! Today’s focus was on understanding Tuples in Python and how they work. Here’s what I learned: 🔗 Tuples in Python: • Tuples are denoted using () brackets • They are immutable — once created, they cannot be changed • Useful for storing fixed data 🔄 Swapping Values: • Learned a very clean Python trick to swap values • Example: A, B = 2, 1 • Swap using: A, B = B, A 🔍 Checking Elements: • Used the “in” keyword to check if an element exists in a tuple 👉 Key takeaway: Tuples are simple, efficient, and useful when you don’t want your data to change. Slowly building strong Python fundamentals step by step 💪 #Day5 #Python #GenerativeAI #AgenticAI #LearningJourney #BuildInPublic
To view or add a comment, sign in
-
Dug a bit into LLM inference engines, and turns out you don't really need C++/CUDA for the core kernels. Wrote a post at https://lnkd.in/gEGX6cGs about performant Python inference using Numba, CuTe-DSL, CuTile, and NCCL4Py.
To view or add a comment, sign in
Explore related topics
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