💡 Understanding "*args" and "**kwargs" in Python Today I explored how Python functions can accept a flexible number of arguments using "*args" and "**kwargs". "*args" allows a function to receive multiple positional arguments, which are stored as a tuple. "**kwargs" allows a function to receive multiple keyword arguments, which are stored as a dictionary. Example: def func(a, *args, **kwargs): total = a for i in args: total += i for k, v in kwargs.items(): total += v return total print(func(1, 2, 3, x=4, y=5)) 📌 Here’s what happens: - "a = 1" - "args = (2, 3)" - "kwargs = {'x': 4, 'y': 5}" The function sums all values and returns 15. 🔎 A small but powerful concept that makes Python functions much more flexible when dealing with dynamic inputs. #Python #DataAnalysis #Coding #LearningInPublic #30DayChallenge #AI #Instant
Understanding *args and **kwargs in Python
More Relevant Posts
-
One small Python concept today… but a very important one. Today’s lesson focused on how Python handles mutable objects like lists. In the example below: def add_item(lst): lst.append(100) a = [1, 2, 3] add_item(a) print(a) The result will be: [1, 2, 3, 100] Why? Because lists in Python are mutable. When we pass a list to a function and modify it using methods like append(), the change happens in-place — meaning the original list itself is modified. 💡 Key takeaway: Understanding the difference between mutable and immutable objects is essential for writing predictable and efficient Python code. Every day in this sprint reminds me that small concepts build strong foundations in data analytics and AI. On to the next challenge. 🚀 #Python #DataAnalytics #AI #MachineLearning #LearningJourney #Coding #TechSkills #AIAnalytics #PythonProgramming #LinkedInLearning
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
-
I recently created a poll based on this problem lst = [True, False, '3', 1, 2, 3] b = 0 not in lst print(b) At first glance, it looks like 0 is not in the list, so the output should be True. But the actual output is : False My initial answer was also True but only after running the code did I realize what was actually happening. So I dug deeper to understand why Python behaves this way. In Python: True == 1 # True False == 0 # True This means when Python checks: 0 in lst # True 0 not in lst # False 𝗞𝗲𝘆 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Be careful when mixing: Booleans (True, False) Integers (1, 0) Especially when using in or comparison operations. It can lead to unexpected results. #Python #CodingTips #ProgrammingConcepts #LearnPython #DeveloperJourney #SoftwareEngineering #TechLearning #CodingPoll
To view or add a comment, sign in
-
🐍 These are important data structures used to store multiple values. 📊 List • Ordered • Mutable (can change) • Allows duplicates Example: [1, 2, 3, 3] 🔒 Tuple • Ordered • Immutable (cannot change) • Allows duplicates Example: (1, 2, 3, 3) 🔁 Set • Unordered • Mutable • Does NOT allow duplicates Example: {1, 2, 3} 💡 Key Difference: List → Changeable + Ordered Tuple → Fixed + Ordered Set → Unique values only 🎯 Choosing the right data structure helps in writing efficient and clean Python code. #Python #DataScience #MachineLearning #AI #LearningInPublic #Programming
To view or add a comment, sign in
-
-
I’ve just published my first blog post on Medium, diving into a Python concept I recently explored: 👉 Mutable vs Immutable Objects Before this, I used to think variables simply “store values.” But in Python, they actually reference objects in memory. Having learned C previously really helped me grasp this concept more quickly, especially when it comes to understanding how memory and references work. In this post, I break down: • The difference between == and is • Mutable vs immutable objects (with clear examples) • Why l1 = l1 + [4] and l1 += [4] behave differently • How Python passes arguments to functions Writing about what I learn pushes me to go deeper and truly understand the concepts. If you’re learning Python or preparing for technical interviews, this is definitely a topic worth mastering. 📖 Read here: https://lnkd.in/guVnYN3Q #Python #SoftwareEngineering #Programming #LearningJourney #Tech
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
-
🚀 DSA Practice – Check if Two Strings are Anagrams Today I solved a classic string problem: Checking whether two strings are anagrams. 📌 Problem Statement: Two strings are called anagrams if they contain the same characters with the same frequency, just arranged differently. 🧠 My Approach: Use a dictionary (hash map) to count character frequency Traverse the first string → increase count Traverse the second string → decrease count If all values in the dictionary are zero, the strings are anagrams ✅ ⚙️ Example: Input: "geeks" and "kseeg" Output: True ✔️ 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) (fixed alphabet size) 💻 Language Used: Python ✨ Key Learning: Using a single hash map for both strings makes the solution efficient and elegant compared to sorting-based approaches. Consistently practicing DSA to strengthen problem-solving and optimization skills 💪 #DSA #Python #Strings #CodingPractice #ProblemSolving #Placements
To view or add a comment, sign in
-
-
🚀 𝐓𝐞𝐱𝐭 𝐕𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐬 𝐢𝐧 𝐏𝐲𝐭𝐡𝐨𝐧: Python allows storing text in variables using either double quotes (" ") or single quotes (' ') — both behave the same way. 🔹 𝐒𝐢𝐧𝐠𝐥𝐞 𝐪𝐮𝐨𝐭𝐞𝐬 𝐯𝐬 𝐃𝐨𝐮𝐛𝐥𝐞 𝐪𝐮𝐨𝐭𝐞𝐬 - Both can be used to store strings. text = "Hello" print(text) text = 'Hello' print(text) 𝘖𝘶𝘵𝘱𝘶𝘵: Hello Hello 🔹 𝐌𝐮𝐥𝐭𝐢-𝐥𝐢𝐧𝐞 𝐭𝐞𝐱𝐭 𝐮𝐬𝐢𝐧𝐠 𝐭𝐫𝐢𝐩𝐥𝐞 𝐪𝐮𝐨𝐭𝐞𝐬 text = """ Hello Python """ print(text) 𝘖𝘶𝘵𝘱𝘶𝘵: Hello Python 🔹 𝐔𝐬𝐢𝐧𝐠 \𝐧 𝐟𝐨𝐫 𝐥𝐢𝐧𝐞 𝐛𝐫𝐞𝐚𝐤𝐬 text = """ Hello\nPython """ print(text) 𝘖𝘶𝘵𝘱𝘶𝘵: Hello Python Simple features like these make Python very convenient when formatting text and printing structured output #Python #Coding
To view or add a comment, sign in
-
One of the most underrated features in Python is the dunder (double underscore) method system. These methods are what make Python objects behave like built‑ins. Examples: • __init__ → object initialization • __str__ → human readable representation • __len__ → behavior for len() • __add__ → custom + operator Example: class Vector: def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) Now Python understands how to use + with your objects. Under the hood, Python transforms: a + b into: a.__add__(b) This is one reason Python feels so expressive and flexible. Understanding dunder methods means understanding how Python really works.
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
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
Keep going 👏👏