🔸 🔸 🔸 Classic example to address late-binding and closures in python This 4 line of code talks about multiple important concepts ↘️ Code: funcs = [] for i in range(3): funcs.append(lambda : i) print([f() for f in funcs]) 🤔 What do you think ❓ Will it give any result, will it error out of random ❓ 🟰 Well, this prints [2,2,2] over console The idea is to demystify why this code does what it does under the hood. Concepts ↘️ ➡️ Is lambda : i a valid syntax ? If yes, what does it denote It denotes a shorthand notation to define a function that does not accept any input parameters and returns a single value as output. What will lambda : i resolve to ❓ ↘️ def f(): return i ❓ What is the iterative statement doing 🟰 It simply creates a container in memory, denoted by i. Initializes i to 0 and keeps incrementing the value that the container referenced by i contains ➡️ i : 0 -> 1 -> 2 ❓What will the list funcs hold ➡️ It's important to note here, funcs is a list that appends lambda into it. ➡️ Since, lambda is nothing more than a function in python, the list holds function ✅ ❓ But, how can a list hold function and what does it mean ➡️ Python treats function as objects, and in programming objects are nothing more than a memory address. 🟰 So, the funcs list holds memory addresses that individually resolve to functions denoted by lambda ✅ ➡️ Another important pointer to note here , the list holds the memory reference to these functions, not the actual value returned by the function. ✅ ❓ Demistify [f() for f in funcs] 🟰 This is a list comprehension in python. ➡️ We are iterating over all thats contained in the list, referencing each element via local variable f Since, f refers to an in-memory function, f() will simply invoke the function call. ✅ ➡️ When i = 0: Invoke f(), the first function pointed to by the first element of the list funcs ❓ The interesting part Function call always creates a new individual scope in python. You can say it as a standalone local environment specific to that function call. So, for the first element in funcs f() -> invokes a function that returns i ❓ Where is i now ➡️ Well, i comes from the loop scope created earlier and is used in the enclosed scope lambda : i denoted by function. ❓ So , are we talking about a closure concept in python here ? ➡️ Yes, this is a closure as lambda is closing over the variable i which is defined in the outer scope, the outer scope is the loop scope. ❓ Another interesting thing to note here is : ➡️ i is defined over a single outer scope, so it is shared amongst all the functions contained in the list funcs. 🤔 Think of it as : We are evaluating each function in the list funcs, where each function simply returns i. 🟰 The value of i = 2, post loop iteration finished in range(3), and hence each of these function calls will return the value 2 i.e. value of the variable closed over by lambda. #python #closure #lambda #softwareengineering #dataengineering
Python Lambda Closures: Understanding Late-Binding and Memory Addresses
More Relevant Posts
-
Day 15/30 - for Loops in Python What is a for Loop? A for loop is used to iterate — to go through every item in a sequence one by one and execute a block of code for each item. Instead of writing the same code 10 times, you write it once and let the loop repeat it automatically. The loop stops when it has gone through every item. The Golden Rule: A for loop works on any iterable — any object Python can step through one item at a time. This includes lists, tuples, strings, dictionaries, sets, and ranges. Syntax Breakdown for item in iterable: item -> This is a temporary variable holding the current item on each loop , you name it anything in -> It's the keyword that connects the variable to the iterable , always required iterable → the collection being looped - list, tuple, string, range, dict, set 1. How It Works, Step by Step 2. Python looks at the iterable and picks the first item 3. It assigns that item to your loop variable 4. It runs the indented block of code using that item 5. It moves to the next item and repeats steps 2–3 6. When there are no more items, the loop ends automatically The range() Function The range() generates a sequence of numbers for looping. The stop value is always excluded: range(5) -> 0, 1, 2, 3, 4 range(2, 6) -> 2, 3, 4, 5 range(0, 10, 2) -> 0, 2, 4, 6, 8 range(10, 0, -1) -> 10, 9, 8 ... 1 What You Can Loop Over List → loops through each item String → loops through each character one by one Tuple → same as list — goes item by item Dictionary → loops through keys by default; use .items() for key and value Range → loops through a sequence of generated numbers Set → loops through unique items (order not guaranteed) Tip: Use a name that makes the code readable — for fruit in fruits, for name in names, for i in range(10). i is the convention for index-style loops. Key Learnings ☑ A for loop iterates through every item in a sequence — running the same block for each one ☑ range(start, stop, step) generates numbers .Stop is always excluded ☑ You can loop over lists, strings, tuples, dicts, sets, and ranges ☑ The loop variable is temporary , holds the current item on each pass ☑ Indentation matters , only the indented block runs inside the loop Why It Matters: Loops are what turn Python from a calculator into an automation tool. Processing 10,000 sales records, sending emails to every customer, checking every row in a database - all of it uses loops. Writing code once and letting it repeat is one of the most powerful ideas in programming. My Takeaway Before loops, I was writing the same thing over and over. Now I write it once and Python handles the rest. That's what automation actually means - not robots, just smart repetition. #30DaysOfPython #Python #LearnToCode #CodingJourney #WomenInTech
To view or add a comment, sign in
-
-
🐍 Coming from Python. Last week I confidently wrote this in Rust: for i in range(1..100) { // 💥 sum += i; } Error: cannot find function 'range' in this scope My brain: “But Rust it’s just Python with semicolons?” That tiny mistake became one of the best lessons I’ve had in systems programming. 🔍 Corrected Rust vs Python Rust fn main() { let number: u32 = 92; if number % 2 == 0 { println!("{} is even", number); } else { println!("{} is odd", number); } let size = match number { 1..=20 => "small", 21..=50 => "medium", 51..=100 => "large", _ => "out of range", }; let mut sum = 0; for i in 1..=100 { sum += i; } println!("Sum = {}", sum); } Python number = 92 if number % 2 == 0: print(f"{number} is even") else: print(f"{number} is odd") if 1 <= number <= 20: size = "small" elif 21 <= number <= 50: size = "medium" elif 51 <= number <= 100: size = "large" else: size = "out of range" total = sum(range(1, 101)) print(f"Sum = {total}") Both do the same job. But the how is completely different. 🧠 Under the Hood – What Rust Forces You to Respect 1. No hidden pointers Python’s number = 92 is a full PyObject on the heap (refcount + type pointer + value). Rust’s u32 lives on the stack one CPU register. Modulo is a single instruction. 2. Zero-cost abstractions Rust’s 1..=20 in match compiles to two integer comparisons (disappears after optimization). No method calls, no temporary objects. 3. The loop reality Rust’s 1..=100 iterator lives entirely on the stack. 100 stack increments. Python’s range(1, 101)creates 100 Python integer objects behind the scenes (heap + refcounting + GC pressure). 4. Match is lightning fast Rust turns match into a jump table or optimized branches. Python’s version (even structural pattern matching) still has runtime overhead. ⚡ The Discipline Rust Teaches Python lets you be productive. Rust forces you to be precise. No more `range()` → Use the `..` syntax directly. Forgetting `mut`? Compiler stops you. Semicolon on last expression? You just returned `()`. This explicitness about memory and ownership is exactly why Rust code is so reliable and fast. Pro tips for Python devs: Treat the compiler like a strict but honest mentor. Understand stack vs heap early — it makes ownership click. Run `cargo clippy` religiously. 💬 Final Thought Rust won’t let you forget that every variable occupies real memory, every loop touches real silicon, and every decision has consequences. Python is a fantastic friend. Rust is a disciplined mentor that makes you a better programmer. Your Python experience is an advantage once you unlearn a few habits. Like ❤️ if you’ve ever tried to use Python syntax in Rust Repost 🔁 to help other Pythonistas Comment💬: What Python habit was hardest for you to break in Rust? #RustLang #Python #RustForPythonDevs
To view or add a comment, sign in
-
-
Task Holberton Python: Mutable vs Immutable Objects During this trimester at Holberton, we started by learning the basics of the Python language. Then, as time went on, both the difficulty and our knowledge gradually increased. We also learned how to create and manipulate databases using SQL and NoSQL, what Server-Side Rendering is, how routing works, and many other things. This post will only show you a small part of everything we learned in Python during this trimester, as covering everything would be quite long. Enjoy your reading 🙂 Understanding how Python handles objects is essential for writing clean and predictable code. In Python, every value is an object with an identity (memory address), a type, and a value. Identity & Type x = 10 print(id(x)) print(type(x)) Mutable Objects Mutable objects (like lists, dicts, sets) can change without changing their identity. lst = [1, 2, 3] lst.append(4) print(lst) # [1, 2, 3, 4] Immutable Objects Immutable objects (like int, str, tuple) cannot be changed. Any modification creates a new object. x = 5 x = x + 1 # new object Why It Matters With mutable objects, changes affect all references: a = [1, 2] b = a b.append(3) print(a) # [1, 2, 3] With immutable objects, they don’t: a = "hi" b = a b += "!" print(a) # "hi" Function Arguments Python uses “pass by object reference”. Immutable example: def add_one(x): x += 1 n = 5 add_one(n) print(n) # 5 Mutable example: def add_item(lst): lst.append(4) l = [1, 2] add_item(l) print(l) # [1, 2, 4] Advanced Notes - Shallow vs deep copy matters for nested objects - Beware of aliasing: matrix = [[0]*3]*3 Conclusion Mutable objects can change in place, while immutable ones cannot. This impacts how Python handles variables, memory, and function arguments—key knowledge to avoid bugs.
To view or add a comment, sign in
-
🔎 Mastering f-Strings in Python #Day32 If you're learning Python, f-strings are something you’ll use almost every day. They make string formatting cleaner, faster, and much more readable. 🔹 What Are f-Strings? f-strings (formatted string literals) were introduced in Python 3.6 and provide a simple way to embed variables and expressions directly inside strings. You create them by placing f before the opening quotation marks. Syntax: f"Your text {variable_or_expression}" Example: name = "Ishu" age = 20 print(f"My name is {name} and I am {age} years old.") ✅ Output: My name is Ishu and I am 20 years old. 🔹 Why Use f-Strings? Before f-strings, we used: 1. % Formatting (Old Style) name = "Ishu" print("Hello %s" % name) 2. .format() Method print("Hello {}".format(name)) 3. f-Strings (Modern Way) ✅ print(f"Hello {name}") 💡Cleaner 💡Easier to read 💡Faster than older methods 💡Supports expressions directly 🔹 Inserting Variables product = "Laptop" price = 55000 print(f"The {product} costs ₹{price}") Output: The Laptop costs ₹55000 🔹 Using Expressions Inside f-Strings You can perform calculations directly inside {} a = 10 b = 5 print(f"Sum = {a+b}") print(f"Product = {a*b}") Output: Sum = 15 Product = 50 🔹 Calling Functions Inside f-Strings name = "ishu" print(f"Uppercase: {name.upper()}") Output: Uppercase: ISHU 🔹 Formatting Numbers Decimal Places pi = 3.14159265 print(f"{pi:.2f}") Output: 3.14 .2f → 2 decimal places. 🔹 Adding Commas to Large Numbers num = 1000000 print(f"{num:,}") Output: 1,000,000 🔹 Formatting Percentages score = 0.89 print(f"{score:.2%}") Output: 89.00% 🔹 Padding and Alignment Left Align print(f"{'Python':<10}") Right Align print(f"{'Python':>10}") Center Align print(f"{'Python':^10}") Useful for reports and tables. 🔹 Using Expressions with Conditions marks = 85 print(f"Result: {'Pass' if marks>=40 else 'Fail'}") Output: Result: Pass Yes — even conditional logic works 😎 🔹 Date Formatting with f-Strings from datetime import datetime today = datetime.now() print(f"{today:%d-%m-%Y}") Example output: 26-04-2026 🔹 Debugging with f-Strings (Awesome Feature) Python allows this: x = 10 y = 20 print(f"{x=}, {y=}") Output: x=10, y=20 Great for debugging 🛠️ 🔹 Escaping Curly Braces Need literal braces? print(f"{{Python}}") Output: {Python} Use double braces {{ }} 🔹 f-Strings with Dictionaries student = {"name":"Ishu","marks":95} print(f"{student['name']} scored {student['marks']}") Output: Ishu scored 95 🔹 f-Strings with Loops for i in range(1,4): print(f"Square of {i} is {i*i}") Output: Square of 1 is 1 Square of 2 is 4 Square of 3 is 9 🔹 Final Thoughts f-Strings are one of Python’s most elegant features. They make your code: ✔More readable ✔More powerful ✔More Pythonic ✔More professional #Python #DataAnalytics #PythonProgramming #DataAnalysis #DataAnalysts #PowerBI #Excel #CodeWithHarry #Tableau #SQL #Consistency #DataVisualization #DataCleaning #DataCollection #MicrosoftPowerBI #MicrosoftExcel #F_Strings
To view or add a comment, sign in
-
🧠 Python Tricky Outputs — Test Your Knowledge! Can you guess the output of these three Python snippets? Let's find out! 👇 🔍 OUTPUTS: Snippet 1 → '['a', 'b', 'c', 'd', 'e', 'f,g,h']' Snippet 2 → '{2, 3}' Snippet 3 → '2' 🔍HOW IT WORKS: "Snippet 1 — split() with maxsplit=5" Step 1 → String: "a,b,c,d,e,f,g,h" Step 2 → Split by comma ',' Step 3 → maxsplit=5 means only split the first 5 times. Step 4 → Result has 6 items (5 splits + remainder) Split 1 → "a" Split 2 → "b" Split 3 → "c" Split 4 → "d" Split 5 → "e" Remainder → "f,g,h" (no more splitting) "Snippet 2 — Set Intersection (&)" Step 1 → {1, 2, 3} Step 2 → {2, 3, 4} Step 3 → & (ampersand) finds common elements. Step 4 → Common elements: 2 and 3 Step 5 → Result: {2, 3} "Snippet 3 — dict.get() with default" Step 1 → Dictionary d = {"a": 1} Step 2 → d.get("b", 2) Step 3 → "b" is NOT a key in the dictionary Step 4 → get() returns default value → 2 Step 5 → If the key existed, it would return the actual value ⚠️ EDGE CASES: "split() maxsplit" maxsplit=0 → No splitting → Entire string as one item maxsplit > number of commas → Splits all, extra maxsplit ignored Empty string → [''] "Set intersection" Empty set → {} No common elements → set() Same sets → Returns the set itself "dict.get()" Key exists → Returns actual value Key missing → Returns default No default provided → Returns None 📌 REAL-WORLD APPLICATIONS: "split() with maxsplit" → Parsing logs, CSV headers, first N fields only "Set intersection" → Finding common users, shared interests, mutual friends "dict.get()" → Safe dictionary access, avoiding KeyError, from defaults 💡 KEY CONCEPTS: • 'split(',', maxsplit)' → Maximum number of splits to perform • '&' operator → Set intersection (common elements) • 'dict.get(key, default)' → Returns default if key missing • No KeyError → Safer than dict[key] 📌 QUICK QUIZ — Test Yourself: # Q1: What's the output? print("one,two,three,four".split(',', 2)) # Q2: What's the output? print({5, 6, 7} & {6, 7, 8}) # Q3: What's the output? d = {"name": "Alice"} print(d.get("age", 25)) #Python #Coding #Programming #LearnPython #Developer #Tech #PythonTips #Dictionary #Sets #Strings #CodeQuiz #SplitMethod #SetOperations #GetMethod #Day76
To view or add a comment, sign in
-
-
Day 10: Python Code Tools — When Language Fails, Logic Wins 🐍 Welcome to Day 10 of the CXAS 30-Day Challenge! 🚀 We’ve connected our agents to external APIs (Day 9), but what happens when you need to perform complex calculations or multi-step logic that doesn't require a database call? The Problem: The "Calculator" Hallucination LLMs are incredible at understanding context, but they are not calculators. They are probabilistic next-token predictors. If you ask an LLM to calculate a 15% discount on a $123.45 cart total with a weight-based shipping surcharge, it might give you an answer that looks right but is mathematically wrong. In an enterprise environment, "close enough" isn't good enough for billing. The Solution: Python Code Tools In CX Agent Studio, you can empower your agent with deterministic logic by writing custom Python functions directly in the console. How it works: You define a function in a secure, server-side sandbox. The LLM's Role: The model shifts from calculator to orchestrator. It extracts the variables from the conversation (e.g., weight, location, loyalty tier), calls your Python tool, and receives an exact, guaranteed result. Safety First: The code runs in a secure, isolated sandbox, ensuring enterprise-grade security while giving your agent "mathematical superpowers." 🚀 The Day 10 Challenge: The EcoShop Shipping Calculator EcoShop needs a reliable way to quote shipping fees. The rules are too complex for a prompt: Base fee: $5.00 Weight surcharge: +$2.00 per lb for every pound above 5 lbs. International: Flat +$15.00 surcharge. Loyalty: Gold (20% off), Silver (10% off). Your Task: Write the Python function for this logic. Focus on handling the weight surcharge correctly (including fractions of a pound) and applying the loyalty discount to the final total. Stop asking your LLM to do math. Give it a tool instead. 🔗 Day 10 Resources 📖 Full Day 10 Lesson: https://lnkd.in/gGtfY2Au ✅ Day 9 Milestone Solution (OpenAPI): https://lnkd.in/g6hZbtGX 📩 Day 10 Challenge Deep Dive (Substack): https://lnkd.in/g6BM8ESp Coming up tomorrow: We wrap up the week by looking at Advanced Tool Orchestration—how to manage multiple tools without confusing the model. See you on Day 10! #AI #AgenticAI #GenerativeAI #GoogleCloud #Python #LLM #SoftwareEngineering #30DayChallenge #AIArchitect #DataScience #CXAS
To view or add a comment, sign in
-
How My Python Brain Almost Broke My Rust Code🐍🦀 "I typed return, added a semicolon, and Rust looked at me like I’d just tried to put ketchup on a five-star steak." Coming from Python, we’re treated to a world where functions are like polite requests: "Please do this, and return this value when you're done." It’s explicit. It’s comfortable. It’s what we know. But then I met Rust. I tried to write a simple area function and my Python instincts screamed: “Declare the variables! Use the keyword! End the line!” The result? A syntax error that felt like a personal intervention. ## Under the Hood: The "Semicolon" Secret 🤐 In Python, almost everything is a statement. A statement is a command—it does something. In Rust, the magic lies in Expressions. With a semicolon (;): You’ve created a Statement. It performs an action, returns "unit" (), and effectively "kills" the value's journey. Without a semicolon: You’ve created an Expression. The value is "live," and because it’s the last thing in the block, Rust "yields" it upward to the function caller. You may ask? Why does Rust hate my return 🤷? It doesn't! You can use return, but idiomatic Rust treats the last expression as the "final result" of the block. Think of a Python function as a vending machine (you have to press a button to get the result out). Think of a Rust function as a waterfall (the value naturally flows out the bottom unless you put a dam—a semicolon—in its way). I wanna spoil your evening dear python Devs who are transitioning 🤣: 1. Stop declaring "Return variables": You don't need result = x * y. Just let x * y be the last line. 2. The Semicolon is a Wall: If you want a value to leave a function, don't block it with a ;. 3. Types are Friends: While Python guesses what you’re returning, Rust demands you sign a contract by declaring the return type before you even type the type the logic 🫣 eg.(-> i32) . It feels strict and very manual, but it’s actually Rust’s way of promising your code won't crash at 3 AM 😂. Conclusion: Transitioning from Python to Rust isn't just about learning new syntax; it’s about moving from a "Command" mindset to a "Flow" mindset. Python tells the computer what to do; Rust describes how data should transform brick by brick. Ditch the semicolon, ditch the indentation,embrace the expression, and let your code flow! 🦀✨ #RustLang #Python #CodingHumor #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
-
Three months ago, our agent cited Python 3.13 as the latest stable release in a research report. It was wrong — 3.12 was current at the time. The factcheck caught it. Corrected the report. That part isn't remarkable. Any review process would catch that. What happened next is the part that matters: the agent stored a lesson. Not the corrected fact — the lesson about the mistake itself. "Always verify version numbers against the official release page. Don't rely on training data for anything with a release cycle." Two weeks later, I asked it to research a completely different tool. The vector memory surfaced that lesson during pre-search. The agent went straight to the official changelog before writing a single sentence about version compatibility. Nobody told it to. It remembered why it had been wrong before. This is the self-improvement loop I've been building toward in this series. Previous posts covered the infrastructure — four memory types, four storage systems, routing, retrieval. This post is about what it enables: an agent that gets better without being retrained. The loop: 1. Agent produces output 2. Factcheck or human review finds an error 3. The correction gets saved — not just the right answer, but the lesson: what went wrong and how to avoid it 4. Next time, pre-search surfaces the lesson before the agent starts working The key word is "lesson." We don't store "Python 3.12 is correct." We store "version numbers from training data are unreliable — always check the source." One is a fact that expires. The other is a behavior that compounds. The same loop runs on human feedback. I told the agent: "Don't mock the database in integration tests." Instead of losing that correction after the session, the agent saved it with structure — what was corrected, why it was wrong, how to apply it in the future. That's a feedback memory. Next time it writes integration tests — in any project, any session — it retrieves the lesson and applies it. Over time, these accumulate into working knowledge about how to do the job correctly. Does it work? In the first 20 research sessions, the agent averaged 3.2 factcheck corrections per report. After 80+ sessions with the lesson loop: 0.8. Not zero. But the same category of mistake rarely happens twice. Version numbers, citation formats, API accuracy — each corrected once, stored as a lesson, applied going forward. No fine-tuning, no retraining. The model is the same. The memory layer is what improved. The deeper insight: the agent doesn't just store information. It stores lessons about how to handle information. Facts expire. Lessons compound. What's the most repeated mistake your agent makes — the one you keep correcting but it never sticks? #AIAgents #AgentArchitecture #SelfImprovingAI
To view or add a comment, sign in
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ```
To view or add a comment, sign in
-
✅ *Top Python Basics Interview Q&A - Part 3* 🌟 *1️⃣ What are classes and objects in Python?* Classes are blueprints for creating objects. Objects are instances of classes with attributes and methods. ``` class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says Woof!" my_dog = Dog("Buddy") print(my_dog.bark()) # Output: Buddy says Woof! ``` *2️⃣ What is inheritance in Python?* Inheritance allows a class (child) to inherit properties from another class (parent). ``` class Animal: def speak(self): return "Sound" class Cat(Animal): def speak(self): return "Meow" ``` *3️⃣ What are self and `__init__`?* self refers to the current instance. `__init__` is the constructor method called when creating objects. *4️⃣ Explain access modifiers (public, private, protected).* Python uses conventions: obj.attr (public), _obj_attr (protected), __obj_attr (private/name mangling). *5️⃣ What are Python packages?* Directories containing modules with an `__init__.py` file. Example: numpy, pandas. *6️⃣ How do you read/write files in Python?* Use open() with modes "r", "w", "a". Always use with statement for auto-closing. ``` with open("file.txt", "w") as f: f.write("Hello World") ``` *7️⃣ What is the difference between append() and extend()?* append() adds a single item. extend() adds multiple items from an iterable. *8️⃣ Explain *args and **kwargs.* *args passes variable positional arguments. **kwargs passes variable keyword arguments. ``` def func(*args, **kwargs): print(args, kwargs) func(1, 2, name="Abinash") # (1, 2) {"name": "Abinash"} ``` *9️⃣ What is a decorator?* A function that modifies another function's behavior. Uses @decorator syntax. *🔟 What is list slicing?* Extract portions of lists: list[start:stop:step]. ``` nums = [0,1,2,3,4] print(nums[1:4]) # [1, 2, 3] ``` 💬 *Double Tap ❤️ for Part 4!*
To view or add a comment, sign in
More from this author
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