Showing posts with label Python Coding Practice. Show all posts
Showing posts with label Python Coding Practice. Show all posts

Python Lambda Function Explained with Examples – Simple Guide for learners

← Back to Home

๐Ÿ Python Lambda Function Explained – Easy Guide for Students & Professionals

Lambda functions in Python are small, powerful, and often misunderstood — but once you get the hang of them, they become a valuable tool in your coding toolkit.

In this guide, we’ll explain what lambda functions are, when to use them, how to write them, and some real-world examples. Whether you’re a beginner or a working professional, this article will help you master Python’s anonymous functions.


✅ What is a Lambda Function in Python?

A lambda function is a small, anonymous function defined using the keyword lambda.

It is:

  • Used for short, one-line functions

  • Often used where a function is needed temporarily

  • Can take any number of arguments but has only one expression

  • Lambda functions are anonymous functions in Python used for quick operations.

  • You can use a lambda function in map() and filter() to simplify logic.

  • They are especially useful in functional programming with Python.


๐Ÿง  Syntax of Lambda Function

lambda arguments: expression

This returns a function object that you can call just like a normal function.


๐Ÿงช Basic Example

Let’s write a lambda function that adds 10 to a number:

add_ten = lambda x: x + 10
print(add_ten(5))  # Output: 15

Here, lambda x: x + 10 is equivalent to:

def add_ten(x):
    return x + 10

๐Ÿ” Multiple Arguments Example

multiply = lambda x, y: x * y
print(multiply(3, 4))  # Output: 12

⚙️ Where to Use Lambda Functions

Lambda functions are most commonly used:

  • Inside map(), filter(), and reduce()

  • When passing a simple function as an argument

  • To simplify short logic without cluttering the code


๐Ÿงฉ Lambda with map()

numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # Output: [1, 4, 9, 16]

๐Ÿงช Lambda with filter()

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)  # Output: [2, 4, 6]

➕ Lambda with sorted()

students = [('Alice', 85), ('Bob', 72), ('Charlie', 90)]
# Sort by score (second element)
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# Output: [('Bob', 72), ('Alice', 85), ('Charlie', 90)]

⚠️ When NOT to Use Lambda

  • For complex logic (use def instead)

  • When readability is more important than brevity

  • If the function needs a docstring or name


๐Ÿ“ Summary Table

Feature Lambda Function         Normal Function (def)
Syntax                 One-liner             Multi-line allowed
Naming                 Anonymous             Named
Usage             Quick, temporary functions             Reusable and readable
Supports Docstring                                      
Used with             map(), filter(), sort(), etc.             Anywhere

๐ŸŽ“ Practice Task for Students

Try writing a lambda function that checks if a number is even or odd:

is_even = lambda x: "Even" if x % 2 == 0 else "Odd"
print(is_even(7))  # Output: Odd

๐Ÿงฉ Real-World Use Case: Sorting Dictionary by Value

data = {'a': 5, 'b': 2, 'c': 9}
sorted_data = sorted(data.items(), key=lambda item: item[1])
print(sorted_data)  # Output: [('b', 2), ('a', 5), ('c', 9)]

✅ Conclusion

Lambda functions are an elegant way to write quick, throwaway functions without creating full function definitions. For students, they help understand functional programming. For professionals, they help write cleaner, faster, and more Pythonic code.

When used wisely, lambda functions can improve your code efficiency — just remember to keep them short and readable!



watch video to understand Python Lambda Function below: 


 

 

Python Lists Explained with Examples – A Beginner to Pro Guide

← Back to Home

๐Ÿ Python Lists Made Easy: A Beginner to Pro Guide

Python is known for its simplicity and powerful built-in data structures. One of the most important and widely used structures in Python is the list.

Whether you're a student just starting out or a professional working on a project, understanding Python lists can help you write cleaner, faster, and more efficient code.


✅ What is a List in Python?

A list in Python is a collection of items that are ordered, changeable (mutable), and allow duplicate values.

You can store:

  • Numbers

  • Strings

  • Other lists

  • Even a mix of different data types!


๐Ÿ“ฆ Creating a List

# Creating different types of lists
numbers = [1, 2, 3, 4, 5]
names = ["Alice", "Bob", "Charlie"]
mixed = [10, "hello", 3.14, True]

๐Ÿ“Œ Basic List Operations

1. Accessing Items

Lists use indexing starting from 0.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])   # Output: apple
print(fruits[-1])  # Output: cherry (last item)

2. Changing Items

fruits[1] = "blueberry"
print(fruits)  # ['apple', 'blueberry', 'cherry']

3. Adding Items

fruits.append("orange")         # Add at end
fruits.insert(1, "mango")       # Add at specific position

4. Removing Items

fruits.remove("apple")          # Remove by value
fruits.pop()                    # Remove last item
del fruits[0]                   # Remove by index

5. List Length

print(len(fruits))  # Number of items

๐Ÿ”„ Looping Through a List

for fruit in fruits:
    print(fruit)

๐Ÿงช Useful List Methods

Method Description
append() Adds an item to the end
insert() Inserts item at a specific index
remove() Removes the first occurrence
pop() Removes item at index or last
sort() Sorts the list (in place)
reverse() Reverses the order of items
clear() Removes all items
index() Returns index of first occurrence
count() Counts number of occurrences

Example:

scores = [45, 87, 45, 92, 60]
print(scores.count(45))    # Output: 2
print(scores.index(92))    # Output: 3

๐Ÿง  Advanced List Tricks (Useful for Professionals)

1. List Comprehension

A concise way to create lists.

squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

2. Slicing

Extract parts of a list.

nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4])    # [1, 2, 3]
print(nums[:3])     # [0, 1, 2]
print(nums[-2:])    # [4, 5]

3. Nested Lists

Lists inside lists (like a matrix).

matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
]
print(matrix[1][1])  # Output: 4

๐ŸŽฏ When to Use Lists?

  • Storing ordered data like names, numbers, tasks

  • Looping through a group of values

  • Performing bulk operations (filter, sort, etc.)

  • Building custom data structures like stacks/queues


๐Ÿ“ Quick Summary

  • Lists are ordered, mutable collections.

  • You can add, remove, change, or access items easily.

  • Great for storing groups of related data.

  • Widely used in Python for data manipulation, web development, automation, and more.


๐Ÿ’ก Practice Challenge

Try this:

# Create a list of 5 favorite movies
# Print only the 2nd and 4th movie from the list

movies = ["The Matrix", "Interstellar", "Inception", "The Dark Knight", "Tenet"]
print(movies[1])
print(movies[3])

๐ŸŽ“ Conclusion

Python lists are a core part of the language that you'll use in almost every project. They're simple enough for beginners and powerful enough for professionals.

Whether you're building a to-do app or crunching big data, knowing how to use lists efficiently is a skill every Python developer needs.




This above video describes python lists in a very easy and smooth manner for the viewers who want to learn it .Watch it with examples and hands on exercises.
Learn the concept of lists in python and get answers of the following questions:

What is a python list ?
How to create lists in python?
Populating list with items.
How to access items from a list in python?
Slicing in python.
Concatenation of two lists in python.


Featured Post

Extra Challenge: Using References Between Documents

  ๐ŸŽฏ ๐Ÿ’ก Extra Challenge: Using References Between Documents Here's an  Extra Challenge  designed to build on the original MongoDB mod...

Popular Posts