✅ *Python Basics: Part-5* *Lambda Functions & Built-in Functions* ⚡🧠 🎯 *1. Lambda Functions* A *lambda* is an anonymous, one-line function. Syntax: ```python lambda arguments: expression ``` 🔹 *Example:* ```python add = lambda x, y: x + y print(add(3, 4)) # Output: 7 ``` Use-case: Often used with functions like `map()`, `filter()`, and `sorted()`. 🎯 *2. Built-in Functions (Must-Know)* 🔹 `len()` – Returns the length of an object ```python len("Hello") # 5 ``` 🔹 `type()` – Shows the type of variable ```python type(10) # <class 'int'> ``` 🔹 `int()`, `float()`, `str()` – Type conversion ```python int("5") → 5 ``` 🔹 `input()` – Takes user input ```python name = input("Enter your name: ") ``` 🔹 `range()` – Generates a sequence of numbers ```python for i in range(5): print(i) # 0 to 4 ``` 🔹 `sum()` – Adds up values in a list ```python sum([1, 2, 3]) # Output: 6 ``` 🔹 `max()`, `min()` – Find largest/smallest ```python max([10, 3, 8]) # 10 ``` 💬 *Double Tap ❤️ for Part-6!*
Python Basics: Lambda Functions & Built-in Functions
More Relevant Posts
-
Today I learned about lambda functions in Python A lambda is just a small, anonymous one-liner function — no name, no `return`, just pure logic. Basic syntax: ``` lambda arguments: expression ``` Instead of writing: ```python def add(a, b): return a + b ``` You can write: ```python add = lambda a, b: a + b ``` But the real power shows up when you pair it with `map()`, `filter()`, and `sorted()`: ```python # Double every number list(map(lambda x: x * 2, [1, 2, 3, 4])) # → [2, 4, 6, 8] # Keep only even numbers list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5])) # → [2, 4] # Sort by second element sorted([(1,3),(2,1),(4,2)], key=lambda x: x[1]) # → [(2, 1), (4, 2), (1, 3)] ``` Key rule I'll remember: Use lambda when the logic is small and used once Avoid it when the logic gets complex — just write a proper `def` Small concept, but it shows up everywhere in Python backend code. #Python #Backend #LearningInPublic #100DaysOfCode #Django
To view or add a comment, sign in
-
✅ *Python Basics: Part-4* *Functions in Python* 🧩⚙️ 🎯 *What is a Function?* A function is a reusable block of code that performs a specific task. 🔹 *1. Defining a Function* Use the `def` keyword: ```python def greet(name): print(f"Hello, {name}!") ``` 🔹 *2. Calling a Function* ```python greet("Alice") ``` 🔹 *3. Return Statement* Functions can return a value using `return`: ```python def add(a, b): return a + b result = add(3, 5) print(result) # Output: 8 ``` 🔹 *4. Default Parameters* You can set default values for parameters: ```python def greet(name="Guest"): print(f"Hello, {name}") ``` 🔹 *5. Keyword Arguments* Arguments can be passed by name: ```python def info(name, age): print(f"{name} is {age} years old") info(age=25, name="Bob") ``` 🔹 *6. Variable-Length Arguments* - `*args`: Multiple positional args - `**kwargs`: Multiple keyword args ```python def show_args(*args): print(args) def show_kwargs(**kwargs): print(kwargs) ``` 💬 *Double Tap ❤️ for Part-5!*
To view or add a comment, sign in
-
⛓️💥 A silent patch in Airflow metaclass breaks Python MRO. This is something I was not expecting as an Airflow plugin maintainer. Recently I received a pull request to my airflow-clickhouse-plugin GitHub repo. A contributor found out that some plugin functionality is unusable because of a strange error: >>> ClickHouseSQLExecuteQueryOperator(task_id='id', sql='SELECT 1') ❌ TypeError: Invalid arguments were passed to ClickHouseSQLExecuteQueryOperator (task_id: id). Invalid arguments were: **kwargs: {'sql': 'SELECT 1'} Like, whaaaat? 😱 The only purpose of this operator is to literally execute SQL. The class definition is: class ClickHouseSQLExecuteQueryOperator( ClickHouseBaseDbApiOperator, sql.SQLExecuteQueryOperator, ): pass __init__ method is not defined in ClickHouseBaseDbApiOperator. So, it was pretty expected that it should call __init__ of SQLExecuteQueryOperator which has that sql parameter! It turned out that the reason was in BaseOperatorMeta. A metaclass that is used for every Airflow operator class to be created. Because of a dirty way to check “Does this class override __init__?” it was injecting an unexpected __init__ into the chain. Funny thing, this issue can be resolved as simply as adding a boilerplate __init__ method calling super().__init__(**kwargs). I have shared details of this investigation in my Medium post. What a sneaky bug it was! See it in the first comment. 💭 Any sneaky bugs you remember? #Airflow #Python #PythonMRO
To view or add a comment, sign in
-
-
🐍 Lambda Function in Python (Simple Explanation) Lambda is just a **small one-line function**. No name, no long code… just quick work ✅ 👉 Instead of writing this: ```python def add(x, y): return x + y ``` 👉 You can write this: ```python add = lambda x, y: x + y print(add(3, 5)) # 8 ``` 💡 Where do we use it in real life? 🔹 1. Sorting (very useful) ```python students = [("Vinay", 25), ("Rahul", 20)] students.sort(key=lambda x: x[1]) # sort by age print(students) ``` 🔹 2. Filter (get only even numbers) ```python numbers = [1,2,3,4,5,6] even = list(filter(lambda x: x % 2 == 0, numbers)) print(even) # [2,4,6] ``` 🔹 3. Map (change data) ```python numbers = [1,2,3] square = list(map(lambda x: x*x, numbers)) print(square) # [1,4,9] ``` ✅ Use lambda when: • Code is small • Use only once • Want quick solution ❌ Don’t use when: • Code is big or complex 💡 Simple line to remember: “Short work → Lambda” 👉 Are you using lambda or still confused? #Python #Coding #LearnPython #Programming #Developers #PythonTips
To view or add a comment, sign in
-
-
Stop using in on Lists. Your Python code is crying. Did you know that checking if an item exists in a List gets slower the more data you have? In 2026, when we're handling massive datasets, this "simple" mistake is a silent performance killer. ━━━━━━━━━━━━━━━━━━━━━━━━━ List = A Messy Pile: To find one book, you have to look at every single book one by one (O(n) time). Set = A Library Index: You go straight to the shelf and find it immediately (O(1) time). ━━━━━━━━━━━━━━━━━━━━━━━━━ Slow (List): allowed_users = ["a", "b", "c"] if user in allowed_users: Python searches every item Fast (Set): allowed_users = {"a", "b", "c"} if user in allowed_users: Python finds it instantly #PythonTips #BackendEngineering #CleanCode #SoftwareArchitecture #SystemDesign #DataStructures #PythonProgramming #NavedsTechTales #CodingLife #WebDev
To view or add a comment, sign in
-
-
🐍 Python List Operations – The Only Cheat Sheet You'll Need Master lists with these 25+ essential operations: 🔍 Accessing & Finding • list[i] → Get single item by index • list[start:end] → Get multiple items (slicing) • a, b, c = list → Unpack all items into variables • list.index(x) → Find position of first item with value x • x in list → Check if value x exists (True/False) 📊 Analyzing & Counting • len(list) → Total number of items • list.count(x) → Count how many times value x appears • max(list) / min(list) → Find highest/lowest values ✏️ Modifying Lists • list.append(x) → Add item x to the end • list.insert(i, x) → Insert item x at index i • list.extend(other_list) → Add items from another list • list[index] = new_value → Change item at specific index 🗑️ Removing Items • list.pop(i) → Remove and return item at index i (default last) • list.remove(x) → Remove first occurrence of value x • list.clear() → Remove all items 🔄 Sorting & Copying • list.sort() → Sort list in place (ascending) • list.reverse() → Flip order in place • new_list = sorted(list) → Get sorted copy • copy_list = list.copy() → Create a shallow copy ⚙️ Iteration & Processing • enumerate(list) → Iterate with index and value • [fn(x) for x in list if condition] → List comprehension (filter + transform in one line) • zip(list_a, list_b) → Pair items from two lists 💡 Pro tip: List comprehension is the most elegant Python feature. Master it and you'll write cleaner, faster code. #Python #PythonLists #CodingCheatSheet #DataStructures #LearnPython
To view or add a comment, sign in
-
-
Ever find yourself writing endless `if key in dict:` checks just to group data or count items in Python? 🤯 There's a much cleaner, more Pythonic way to tackle this common pattern and dramatically simplify your code. Instead of initializing a dictionary key with an empty list or zero count every time, embrace `collections.defaultdict`. It's a lifesaver for scenarios where you're building up collections (like lists or sets) or aggregating counts based on keys. It automatically provides a default value for a non-existent key, reducing boilerplate and improving readability. Here’s a quick example of grouping items by category: ```python from collections import defaultdict # Imagine this is data from an API or database products = [ {"name": "Laptop", "category": "Electronics"}, {"name": "Mouse", "category": "Electronics"}, {"name": "Shirt", "category": "Apparel"}, {"name": "Keyboard", "category": "Electronics"}, {"name": "Jeans", "category": "Apparel"}, ] # Group products by category using defaultdict grouped_products = defaultdict(list) for product in products: grouped_products[product['category']].append(product['name']) print(dict(grouped_products)) # Output: {'Electronics': ['Laptop', 'Mouse', 'Keyboard'], 'Apparel': ['Shirt', 'Jeans']} ``` This pattern isn't just about saving a few lines; it's about making your code more robust and less prone to `KeyError` exceptions. It's a fantastic productivity booster that lets you focus on the logic, not the dictionary mechanics. What other Python standard library gems do you swear by for writing cleaner, more efficient code? Share your favorites below! #Python #ProgrammingTips #SoftwareEngineering #CleanCode #Productivity
To view or add a comment, sign in
-
I used to write extra code for things Python could do in one line. Loops for indexing. Manual swaps for reversing. Temporary variables for pairing data. It worked… but it wasn’t elegant. Then I started really understanding Python lists and its built-in functions — and it honestly felt like upgrading the way I think. The first time I used sort(), I realized I didn’t need to reinvent sorting logic every time. But more importantly, I learned that how you sort matters — like using a custom key instead of forcing the data to fit your logic. reverse() taught me something subtle. There’s a difference between changing the original list and creating a new one. That distinction sounds small, but it matters a lot when you're debugging or working with shared data. Then came zip() — and this one completely changed how I handle multiple lists. Instead of juggling indexes, I could iterate cleanly over related data. It made my code feel more readable, almost like telling a story instead of solving a puzzle. And enumerate()… this replaced so many messy loops. No more manual counters. Just clean, intentional iteration with both index and value. What really stood out to me wasn’t just shorter code — it was clearer thinking. I stopped asking, “How do I write this logic?” And started asking, “What’s the cleanest way Python already supports this?” That shift matters a lot in interviews and real projects. Because good code isn’t just about working — it’s about being readable, maintainable, and efficient. Now when I solve problems, I try to use built-ins wherever it makes sense. Not as shortcuts, but as tools that reflect a deeper understanding of the language. Still learning, still improving — but definitely writing better code than I was yesterday.
To view or add a comment, sign in
-
-
Technical post: I've been posting some graphs on here, talking about functions and "equivalence". This was all started by working on porting an MLOPs framework from python 3.10 to 3.12, and all the "dependency hell" one has to go through. Then naturally the question arose "What are the boundaries of one project to another, in terms of functions being called etc.,?" This led me down the rabbit hole (not too deep) of what happens when I do something like python -m <module> <somescript>. Specifically, what is a "no op" module, and what kind of ops can we inject, thanks to python being an interpreted language. A few years ago I'd worked on something along similar lines called TracePath, which provided a decorator to do something similar (e.g. who called who, how long it took, etc.). So I merged these two ideas (avoid decorating every function, have an "inspector" module) and ran this on a simple pandas dataframe creation. The resulting function invocation graph is the image attached to this post. When I ran it across the whole workflow (create, load, transform data etc.,), the graph had ~9000 connections. The nice thing is I can specify which modules (e.g. only pandas, or pandas and numpy) should be added to the graph etc. What do you think is the next logical thing to do with something like this? What kind of graphs would well structured software produce? How about badly written software? #graphs #swe #dependencyhell #python
To view or add a comment, sign in
-
-
✅ *Python Basics: Part-3* *Control Flow in Python* 🔁🧠 🎯 *What is Control Flow?* Control flow allows your code to make decisions and repeat actions using conditions and loops. 🔹 *1. Conditional Statements (if, elif, else)* Used to execute code based on conditions: ```python age = 18 if age >= 18: print("You are an adult") elif age > 13: print("You are a teenager") else: print("You are a child") ``` 🔹 *2. Loops* ● *For Loop* – Used to iterate over a sequence (list, string, etc.) ```python fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) ``` ● *While Loop* – Repeats as long as a condition is true ```python count = 0 while count < 5: print(count) count += 1 ``` 🔹 *3. Loop Control Statements* - `break`: Exit the loop - `continue`: Skip current iteration - `pass`: Placeholder that does nothing ```python for i in range(5): if i == 3: break print(i) ``` 💬 *Double Tap ❤️ for Part-4!*
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