Introduction π
The map() function allows you to apply a function to each item of an iterable (like list, tuple, or set) and returns a map object which can be converted to a list, tuple, etc. It is perfect for transforming data cleanly and efficiently.
Note
1. Basic Syntax π§±
map_basic.py
result = map(function, iterable)2. Using map() with Built-in Function π’
map_builtin.py
nums = [1, 2, 3, 4]
result = list(map(str, nums))
print(result) # ['1', '2', '3', '4']Note
3. Using map() with Lambda Functions β‘
map_lambda.py
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, nums))
print(squares)4. Using map() with User-Defined Functions π§©
map_custom.py
def cube(x):
return x ** 3
nums = [1, 2, 3, 4]
result = list(map(cube, nums))
print(result)5. Mapping Multiple Iterables π―
When multiple iterables are provided, map() applies the function to corresponding items.
map_multiple.py
a = [1, 2, 3]
b = [4, 5, 6]
result = list(map(lambda x, y: x + y, a, b))
print(result) # [5, 7, 9]Note
6. map() with String Iterables π€
map_string.py
word = "python"
result = list(map(lambda ch: ch.upper(), word))
print(result)7. map() with Tuples and Sets π
map_tuple_set.py
nums = (10, 20, 30)
result = tuple(map(lambda x: x // 10, nums))
print(result) # (1, 2, 3)
nums_set = {1, 2, 3}
result = set(map(lambda x: x * x, nums_set))
print(result)8. Using map() for Data Cleaning π§Ό
map_cleaning.py
data = [" hello", "world ", " python "]
cleaned = list(map(lambda s: s.strip(), data))
print(cleaned)9. map() vs List Comprehension βοΈ
| Feature | map() | List Comprehension |
|---|---|---|
| Readability | Good for simple functions | Clear & Pythonic |
| Speed | Fast (C optimized) | Usually similar |
| Supports multiple iterables | Yes | No |
| Supports complex logic | Hard | Easier |
Note
10. Real-World Examples π
Convert list of strings to integers
map_str_to_int.py
values = ["10", "20", "30"]
nums = list(map(int, values))
print(nums)Calculate final price after discount
map_discount.py
prices = [100, 200, 300]
discounted = list(map(lambda p: p * 0.9, prices))
print(discounted)Formatting email list
map_emails.py
emails = ["USER1@GMAIL.COM", "Admin@Yahoo.com"]
normalized = list(map(lambda e: e.lower(), emails))
print(normalized)Extracting lengths of words
map_word_len.py
words = ["apple", "banana", "kiwi"]
lengths = list(map(len, words))
print(lengths)Conclusion π
You now fully understand Pythonβs map() function! Want the next topic? Try filter(), reduce(), Recursion, or OOP (Classes & Objects). Just tell me! π
Introduction π
The filter() function is used to filter elements from an iterable (list, tuple, set, etc.) based on a condition. It returns only the items for which the function returns True.
Note
1. Basic Syntax π§±
filter_basic.py
result = filter(function, iterable)2. Using filter() with Lambda Function β‘
filter_lambda.py
nums = [10, 15, 20, 25, 30]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # [10, 20, 30]Note
βοΈ Perfect for filtering lists quickly.
3. Using filter() with User-Defined Functions π§©
filter_custom.py
def is_positive(n):
return n > 0
nums = [-5, 0, 10, -3, 8]
positive_nums = list(filter(is_positive, nums))
print(positive_nums)4. Filtering Strings π€
filter_strings.py
names = ["alice", "Bob", "charlie", "David"]
long_names = list(filter(lambda n: len(n) > 4, names))
print(long_names)5. Filtering Based on Type π§
filter_types.py
items = [10, "hello", 3.5, "world", True]
strings = list(filter(lambda x: isinstance(x, str), items))
print(strings) # ['hello', 'world']6. filter() with Multiple Iterables (Trick) π―
filter() does NOT support multiple iterables directly, but you can combine them with zip().
filter_zip.py
scores = [50, 85, 30, 95]
names = ["A", "B", "C", "D"]
passed = list(filter(lambda x: x[1] >= 50, zip(names, scores)))
print(passed)7. Filtering Empty or None Values π«
filter_none.py
data = ["hello", "", None, "python", " "]
cleaned = list(filter(lambda x: x and x.strip(), data))
print(cleaned)Note
8. Filtering Tuples, Sets & Dictionaries π
Tuple
filter_tuple.py
nums = (10, 3, 5, 20)
filtered = tuple(filter(lambda x: x > 5, nums))
print(filtered)Set
filter_set.py
nums = {1, 2, 3, 4, 5}
filtered = set(filter(lambda x: x % 2 == 1, nums))
print(filtered)Dictionary (filter keys)
filter_dict_keys.py
student = {"A": 85, "B": 40, "C": 95}
passed = dict(filter(lambda item: item[1] >= 50, student.items()))
print(passed)9. filter() vs List Comprehension βοΈ
| Feature | filter() | List Comprehension |
|---|---|---|
| Readability | Good for simple filtering | Clear & Pythonic |
| Speed | Fast (C optimized) | Similar or faster |
| Complex conditions | Harder | Easier |
| Function needed? | Yes | No |
Note
10. Real-World Examples π
Filter valid emails
filter_emails.py
emails = ["a@gmail.com", "invalid", "b@yahoo.com", "@nope"]
valid = list(filter(lambda e: "@" in e and "." in e, emails))
print(valid)Filter users by age
filter_users.py
users = [
{"name": "A", "age": 17},
{"name": "B", "age": 22},
{"name": "C", "age": 15},
]
adults = list(filter(lambda u: u["age"] >= 18, users))
print(adults)Filter non-zero values
filter_nonzero.py
nums = [0, 1, 2, 0, 3, 0, 4]
non_zero = list(filter(lambda x: x != 0, nums))
print(non_zero)Conclusion π
You now fully understand Pythonβs filter() function! Want the next topic? Try reduce(), Recursion, Higher-Order Functions, or OOP. Just tell me! π
Introduction π
The reduce() function applies a function to the items of an iterable and reduces the entire sequence to a single value. It is part of the functools module and is commonly used in functional programming.
Note
1. Importing reduce() π§±
import_reduce.py
from functools import reduce2. Basic Syntax π§
reduce_syntax.py
reduce(function, iterable, initializer=None)βοΈ function must accept 2 arguments
βοΈ iterable is a list, tuple, etc.
βοΈ initializer is optional (starting value)
3. Simple Reduce Example π§©
reduce_sum.py
from functools import reduce
nums = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, nums)
print(total) # 104. Reduce for Multiplication βοΈ
reduce_product.py
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda a, b: a * b, nums)
print(product) # 245. Using an Initializer π
Initializer is added before the first element.
reduce_initializer.py
from functools import reduce
nums = [1, 2, 3]
result = reduce(lambda a, b: a + b, nums, 10)
print(result) # 16Note
6. Finding Maximum Using Reduce π
reduce_max.py
from functools import reduce
nums = [10, 25, 5, 90, 30]
maximum = reduce(lambda a, b: a if a > b else b, nums)
print(maximum)7. Reduce on Strings π€
reduce_concat.py
from functools import reduce
words = ["Hello", "World", "Python"]
sentence = reduce(lambda a, b: a + " " + b, words)
print(sentence)8. Reduce for Flattening Lists π§Ί
reduce_flatten.py
from functools import reduce
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda a, b: a + b, nested)
print(flat) # [1, 2, 3, 4, 5, 6]9. Reduce vs Built-in Functions βοΈ
| Task | reduce() | Better Alternative |
|---|---|---|
| Sum | reduce(lambda...) | sum() |
| Max | reduce(lambda...) | max() |
| Min | reduce(lambda...) | min() |
| Concatenation | reduce() | ''.join(), ' '.join() |
Note
10. Real-World Examples π
Calculate Total Bill
reduce_bill.py
from functools import reduce
prices = [100, 200, 350]
total = reduce(lambda a, b: a + b, prices)
print("Total =", total)Calculate Factorial
reduce_factorial.py
from functools import reduce
n = 5
factorial = reduce(lambda a, b: a * b, range(1, n+1))
print(factorial)Find Longest Word
reduce_longest.py
from functools import reduce
words = ["apple", "banana", "kiwi", "watermelon"]
longest = reduce(lambda a, b: a if len(a) >= len(b) else b, words)
print(longest)11. When NOT to Use reduce() β οΈ
- When built-in functions already exist (sum, min, max).
- When code becomes hard to read with complex lambdas.
- If performance can be improved using loops.
Conclusion π
You now fully understand Pythonβs reduce() function! Want the next topic? Try Recursion, Modules, Decorators, or OOP (Classes & Objects). Just tell me! π