Why does Python store *args in a tuple instead of a list? When we define a function using *args, Python allows us to pass a variable number of positional arguments. Example: def check_type(*args): print(type(args)) check_type(1, 2, 3, 4) Output: <class 'tuple'> This confirms that *args stores the values in a tuple, not a list. All passed positional arguments are automatically packed into a tuple, and the variable args becomes a reference to that tuple. But why does Python choose a tuple instead of a list? There are two main reasons: 1️⃣ Immutability and Data Safety Tuples are immutable, meaning their contents cannot be modified after creation. Function arguments are generally expected to remain constant within the function’s scope. By storing them in an immutable structure, Python ensures that the original input values cannot be accidentally altered (e.g., appended, removed, or reordered). This design choice promotes safer and more predictable code while preserving data integrity. 2️⃣ Performance and Memory Efficiency Tuples are more memory-efficient and slightly faster than lists because they have a fixed size at creation. Lists, on the other hand, are dynamically resizable and may allocate extra memory to support future growth. Since most functions do not modify their input arguments, using a tuple provides better efficiency without affecting the required behavior. 🔹In summary: *args stores values in a tuple because tuples are immutable, safer, and more memory-efficient, making them the most appropriate structure for handling variable positional arguments. #Python #MachineLearning #SoftwareDevelopment #CodingTips #AI
Python's *args stores values in immutable tuples for safety and efficiency
More Relevant Posts
-
💬 Discussion Question In Python, if we have a list called "lst1", there are multiple ways to sort the data. Two of the most common approaches are: 1️⃣ "lst1.sort()" 2️⃣ "sorted(lst1)" But what is the difference between them, and when should we use each one? 🔹 "lst1.sort()" - It is a list method. - It sorts the elements in-place, meaning it modifies the original list itself. - It does not return a new list (it returns "None"). Example: lst1 = [4, 2, 7, 1] lst1.sort() print(lst1) Output: [1, 2, 4, 7] 🔹 "sorted(lst1)" - It is a built-in Python function. - It returns a new sorted list without modifying the original one. Example: lst1 = [4, 2, 7, 1] new_list = sorted(lst1) print(lst1) print(new_list) Output: [4, 2, 7, 1] [1, 2, 4, 7] 📌 When to use each one? ✔ Use "sort()" when you want to sort the original list and don’t need the previous order. ✔ Use "sorted()" when you want to keep the original data unchanged and create a new sorted version. 💡 Another advantage of "sorted()" is that it works with many iterable types such as lists, tuples, sets, and dictionaries. #Python #Programming #DataAnalytics #MachineLearning #Coding #30DayChallenge #AI #Instant
To view or add a comment, sign in
-
🚀 DSA with Python – Bit Manipulation Practice Today I continued my Data Structures & Algorithms practice with Python, focusing on Bit Manipulation problems. For each problem, I first explored the brute force / generic approach and then implemented a more efficient solution using bitwise operations. Here are the concepts I practiced today 👇 🔹 1. Lonely Integer Problem: Given an array where every element appears twice except one, find the unique element. 💡 Key Bitwise Observations a ^ a = 0 a ^ 0 = a XOR is commutative and associative So when we XOR all elements, the duplicate numbers cancel each other and the unique element remains. Example: [5,1,4,4,5,3,1] → Lonely Integer = 3 Efficient idea: Iterate through the array and keep XORing elements. Time Complexity: O(n) 🔹 2. Longest Consecutive 1’s in Binary Goal: Find the maximum length of consecutive 1s in the binary representation of a number. 💡 Observation If we perform: n = n & (n << 1) Each iteration removes one consecutive layer of 1s The number of iterations equals the maximum consecutive 1s Example: n = 1101110 By repeatedly applying n & (n << 1), we count how many times it stays non-zero. Time Complexity: O(log n) 🔹 3. Swap Even and Odd Bits Swap every even-positioned bit with the adjacent odd-positioned bit. 💡 Approach 1️⃣ Extract even bits using mask 0xAAAAAAAA 2️⃣ Extract odd bits using mask 0x55555555 3️⃣ Shift them appropriately 4️⃣ Combine using OR Expression: ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1) Time Complexity: O(1) Example: n = 181 Binary swap results in output: 122 🔹 4. Trailing Zeros in Binary Find the number of trailing zeros in the binary representation of a number. Example: n = 168 → 10101000 Trailing zeros = 3 💡 Observation Using the expression: (n ^ (n-1)) & n The result forms a power of two, and using log₂ we can determine the number of trailing zeros. 📚 Key Learning Bit manipulation helps in: ✔ Writing highly optimized solutions ✔ Reducing time complexity ✔ Solving many interview-level problems efficiently Practicing and documenting each concept step-by-step really helps in strengthening problem-solving skills. #DSA #Python #DataStructures #Algorithms #BitManipulation #BitwiseOperators #CodingPractice #ProblemSolving #SoftwareEngineering #PythonDeveloper #DeveloperJourney #InterviewPreparation #CodingInterview #LearnInPublic #BuildInPublic #TechLearning #Programming #ContinuousLearning #100DaysOfCode #DSA #Python #Algorithms #TimeComplexity #BigO #BackendDevelopment #SoftwareEngineering #ProblemSolving #CodingJourney #PythonDeveloper #BackendEngineer #SoftwareDeveloper #FullStackDeveloper #TechInterviews #CodingInterview #InterviewPreparation #ActivelyLooking #CareerGrowth #TechJobs #JobOpportunities #IndiaJobs #BangaloreJobs #HyderabadJobs #RemoteJobs #100DaysOfCode #ContinuousLearning #BuildInPublic #DeveloperJourney
To view or add a comment, sign in
-
-
What really happens when we pass an integer vs a list to a function? In Python, passing an integer to a function does not behave the same way as passing a list. Let’s see why. Example 1: Passing an Integer def change_value(x): x = x + 10 return x num = 5 change_value(num) print(num) ➡️Output: 5 At first glance, this might seem confusing. Here’s what actually happens: 1. num references the integer object 5 in memory. 2. When we call change_value(num), the value 5 is passed to the function. 3. Inside the function, a new local variable x is created, referencing the same object 5. At this moment: num → 5 x → 5 Now comes the important part: x = x + 10 Integers in Python are immutable, meaning they cannot be modified after creation. So Python does not change the value 5. Instead: 1. It calculates 5 + 10. 2. It creates a new integer object 15. 3. It makes x reference this new object. Now: num → 5 x → 15 The original 5 is still in memory, unchanged. This is called rebinding (the variable x was redirected to a new object). And because we did not assign the returned value back to num: ❌ num = change_value(num) ➡️ num remains 5. Example 2: Passing a List def add_item(lst): lst.append(10) numbers = [1, 2, 3] add_item(numbers) print(numbers) ➡️Output: [1, 2, 3, 10] Why did this one change? Because lists are mutable. When we pass numbers to the function: 1. lst references the same list object. 2. When we call lst.append(10), we modify the same object in place. No new list is created. Before: numbers → [1, 2, 3] After: numbers → [1, 2, 3, 10] The variable still points to the same object, but that object was directly modified. This is called modification (in place). 💡 The Core Difference When passing data to a function in Python: • If the object is immutable (like int),the function cannot modify it. Any change creates a new object (rebinding). • If the object is mutable (like list),the function can modify the same object in place. That is why the integer stayed 5, while the list was successfully updated. Understanding this difference is essential to understanding how Python handles memory and variable references. #Python #SoftwareDevelopment #CodingTips #MachineLearning #AI
To view or add a comment, sign in
-
LandingAI just open-sourced ade-python — a Python SDK that enables agentic document extraction, turning complex documents into structured data for AI workflows. 🚀 🔗 https://lnkd.in/gWmAhXCb
To view or add a comment, sign in
-
Python Deep Dive | Understanding *args Like a Pro One small symbol… big impact. When we use *args in a Python function, where are the values actually stored? Many beginners guess list. Some even think it’s a generic collection. But the correct answer is: tuple ✅ 💡 Why tuple? When you define a function like this: def my_function(*args): print(type(args)) And call it like this: my_function(1, 2, 3) The output will be: <class 'tuple'> Python automatically collects all positional arguments into a tuple. ⸻ 🔍 Why did Python choose tuple instead of list? Because tuples are: • Immutable (cannot be modified) • Memory efficient • Faster than lists • Safer for internal function handling Since *args is meant to collect values, not modify them, immutability makes perfect design sense. ⸻ 🚀 Bonus Insight While: • *args → stores data in a tuple • **kwargs → stores data in a dictionary Understanding this difference is essential for writing clean, scalable, and flexible functions — especially in larger AI or backend systems. Small details like this separate someone who “writes Python” from someone who truly understands Python. #Python #Programming #AI #DataScience #CodingJourney #SoftwareEngineering #30DayChallenge
To view or add a comment, sign in
-
Unlock a new way to write AI-powered code: define inputs, return type, and post-conditions; let AI implement and self-correct. Focus on validation and correctness to cut boilerplate. Try AI Functions for receipts parsing. 🔎💡 #Python #AIFunctions #DevTools #CodeQuality #AI
To view or add a comment, sign in
-
Python Discussion Both if and while in Python rely on a condition, but they behave very differently. Let’s break it down 👇 1️⃣ Execution Method 🔹 if statement Checks the condition once. If the condition is True, the code runs one time only. 🔹 while loop Keeps checking the condition and repeats execution as long as the condition is True. 2️⃣ Number of Executions if ➜ Executes 0 or 1 time while ➜ Executes multiple times until the condition becomes False 3️⃣ When to Use Each One (Use Case) ✅ Use if when you want to make a decision once. Example: age = 20 if age >= 18: print("You can enter") 🔁 Use while when you want the program to repeat an action until a condition changes. Example: count = 1 while count <= 5: print(count) count += 1 Output: 1 2 3 4 5 🎯 Simple way to remember: if → Decision while → Repetition 💡 In AI and Data Analytics, loops like while are useful when processing data until a certain condition is met, while if is used for logic and decision making inside algorithms. 💬 Quick question for Python learners: Can you think of a scenario where you would use both if and while together in the same program? #Python #AI #DataAnalytics #LearningInPublic #30DayChallenge #PythonBasics
To view or add a comment, sign in
-
Last week I shared a simple causal inference agent I built where Claude is the brain and Python is the hands (https://lnkd.in/gAUxCj8c). This week I want to pull back the curtain on how it actually works because understanding the architecture changed how I think about when agents are worth building at all. --- The agent has 3 layers: Layer 1: Tool Definitions Claude never sees your Python code. It sees JSON descriptions of what tools exist. Based on those descriptions + the data, it decides which tool to call and what arguments to pass. That's it. Layer 2: The Dispatcher When Claude says "call run_did," the dispatcher translates that into an actual Python function call. It also manages state — storing results, tracking where we are in the analysis, handling errors. Layer 3: Python Tools Each tool is a standalone module doing real statistical work — A/B test, DiD, Synthetic Control, report generation. Claude reasons about them. Python executes them. --- The benefits I'm seeing so far: · Clean separation — Claude handles reasoning, Python handles computation · Easily extensible — adding a new method is just adding a new tool · Auditable — every decision is logged and traceable · Testable — each tool works independently of the agent and can be changed/tested --- The biggest thing I'm still working through is identifying when an agent actually beats just writing a Python script? Current answer: Use a script when you already know which method to run. Use an agent when the right method depends on results you haven't seen yet – at the very least it can help reason a proper method that you can then explore. I'm genuinely still learning here, and the questions being asked of the agent are super basic and somewhat black and white. But one thing I'm fairly convinced of is that if you want consistent, reliable behavior from an agent, you need to give it structure — clear tool definitions, explicit guidelines in the system prompt, well-defined fallback logic. Without that, you're just asking a general LLM to figure it out, which is a bit scary and weaker in my opinion. Curious if others have found this to be true — or where you'd push back. #MarketingAnalytics #CausalInference #AgenticAI #DataScience #BuildingInPublic
To view or add a comment, sign in
-
-
🔹How to Build a General-Purpose AI Agent in 131 Lines of Python Implement a coding agent in 131 lines of Python code, and a search agent in 61 lines 🔹 In this post, we’ll build two AI agents from scratch in Python. One will be a coding agent, the other a search agent. Why have I called this post “How to Build a General-Purpose AI Agent in 131 Lines of Python” then? Well, as it turns out now, coding agents are actually general-purpose agents in some quite surprising ways. What I mean by this is once you have an agent that can write code, it can: Do a huge number of things you don’t often think of as involving code, and Extend itself to do even more things. It’s more appropriate to think of coding agents as “computer-using agents” that happen to be great at writing code. That doesn’t mean you should always build a general-purpose agent, but it’s worth understanding what you’re actually building when you give an LLM shell access. That’s also why we’ll build a search agent in this post: to show the pattern works regardless of what you’re building. #python #ai #claude #anthropic #llm #aiagent #gemini #git #batch Full Credit to Hugo Bowne-Anderson 👏 Read the full article here: https://lnkd.in/dtvhnmVu
To view or add a comment, sign in
-
-
⚡ Writing Python loops the hard way? Let's fix that. ━━━━━━━━━━━━━━━━━━━━━━ Most Python beginners write this: result = [] for n in [1, 2, 3, 4, 5, 6]: if n % 2 == 0: result.append(n * 2) ▸ 4 lines. Repetitive. Easy to get wrong. ━━━━━━━━━━━━━━━━━━━━━━ Python gives you a cleaner tool — the List Comprehension: result = [n * 2 for n in numbers if n % 2 == 0] ────── ─────────────── ───────────── express iterate filter Both produce the same result: [4, 8, 12] ▸ 1 line. Readable. Faster to execute. ━━━━━━━━━━━━━━━━━━━━━━ How to read any list comprehension: [ WHAT YOU WANT → FROM WHERE → ONLY IF ] Once you see that pattern, every comprehension becomes obvious. This is the kind of insight Vaathiyaar teaches at PyMasters — building intuition, not just syntax. → Learn Python the right way at pymasters.net #Python #PythonTips #ListComprehensions #LearnPython #PyMasters
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
شغل عالى يابشمهندسة عاش 👏👏🌹