Level Up Your Python: Easy to Advanced List Comprehension, Lambda , Map ,Filter & Reduce Examples
Discover how to write smarter, cleaner Python code using list comprehensions, lambda functions, and the map function. Explore step-by-step examples—from beginner techniques to advanced one-liners—that will help you process, transform, and analyze data efficiently.
1.List Comprehension
List comprehensions provide a concise way to create lists. Instead of using loops and the append() method, you can build a new list in a single readable line.
Syntax: [expression for item in iterable if condition]
Example :
Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Output: ['apple', 'banana', 'mango']
Example3:
Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Why use list comprehensions?
-
More compact and readable than traditional loops.
-
Usually faster because they are optimized internally.
-
Useful when transforming or filtering lists.
2. Lambda Functions
A lambda function is an anonymous, one-line function defined using the lambda keyword. These functions are often used when a short, throwaway function is needed as an argument for higher-order functions like map() or filter().
Syntax: lambda arguments: expression
Example:
Output: 8
Example:
Output: 12
Example:
Output:
20
30
When to use lambda functions:
-
When you need a quick function for simple tasks.
-
To avoid defining small helper functions with
def. -
Commonly used with functions like
map(),filter(), andreduce().
3.The map() Function
The map() function applies a given function to all items in an iterable (such as a list or tuple) and returns a new map object (which can be converted to a list).
Syntax: map(function, iterable)
Example:
Output: [2,4,9,16,25]
Example:
Output: [2, 4, 6,8]
Example:
Output: [5,7,9]
Example:
Output: ['APPLE', 'BANANA', 'CHERRY']
4.filter(): Selecting Data
The filter() function filters items out of an iterable, returning only those where the function returns True.
Syntax: filter(function, iterable)
Example: Filter Even Numbers
Output: [2,4,6]
Example: Filter Out Empty Strings
Output: ['hello', 'world', 'python']
Example: Filter Students with GPA Above 3.5
Output: [{'name': 'Alice', 'gpa': 3.9}, {'name': 'Charlie', 'gpa': 3.7}]
5.reduce(): Aggregating Data
Unlike map and filter, reduce() isn’t a built-in function. You must import it from functools.
It reduces a sequence to a single value by repeatedly applying a function to the elements.
Syntax:
from functools import reduce
reduce(function, iterable)
Example:Sum All Numbers
Output: 15
The lambda is called like:
-
1 + 2 = 3 -
3 + 3 = 6 -
6 + 4 = 10 -
10 + 5 = 15
Example:Find the Maximum in a List
Output: 8
Example:Flatten a List of Lists
Output: [1, 2, 3, 4, 5, 6]
Great for data manipulation tasks, though itertools.chain is more efficient in practice.

