πŸ—ΊοΈ Python map() β€” Apply a Function to Every Item in a Sequence

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

πŸ’‘ map(function, iterable)The function is applied to every item of the iterable.

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

βœ”οΈ Converts every number into a string.

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

βœ”οΈ Stops when the shortest iterable is exhausted.

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 βš”οΈ

Featuremap()List Comprehension
ReadabilityGood for simple functionsClear & Pythonic
SpeedFast (C optimized)Usually similar
Supports multiple iterablesYesNo
Supports complex logicHardEasier

Note

πŸ’‘ Use map() when applying an existing function. Use list comprehension for readable transformations.

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 πŸŽ‰

>>β€œmap() transforms data cleanly by applying a function to every item β€” simple, fast, and elegant.” ✨

You now fully understand Python’s map() function! Want the next topic? Try filter(), reduce(), Recursion, or OOP (Classes & Objects). Just tell me! 😊

πŸ” Python filter() β€” Select Items That Meet a Condition

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

πŸ’‘ filter(function, iterable)The function should return True or False.

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

βœ”οΈ Keeps only items where condition is True.
βœ”οΈ 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

βœ”οΈ Removes empty strings, None, and whitespace-only values.

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 βš”οΈ

Featurefilter()List Comprehension
ReadabilityGood for simple filteringClear & Pythonic
SpeedFast (C optimized)Similar or faster
Complex conditionsHarderEasier
Function needed?YesNo

Note

πŸ’‘ Use filter() when you already have filtering logic in a function. Use list comprehension for cleaner, more readable filtering.

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 πŸŽ‰

>>β€œfilter() helps you keep only what matters β€” powerful, fast, and clean.” ✨

You now fully understand Python’s filter() function! Want the next topic? Try reduce(), Recursion, Higher-Order Functions, or OOP. Just tell me! 😊

βž— Python reduce() β€” Reduce a Sequence to a Single Value

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

πŸ’‘ reduce() is perfect for cumulative operations like sum, product, min, max, concatenation, etc.

1. Importing reduce() 🧱

import_reduce.py

from functools import reduce

2. 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)  # 10

4. 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)  # 24

5. 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)  # 16

Note

βœ”οΈ Starts with 10 β†’ 10+1+2+3

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 βš–οΈ

Taskreduce()Better Alternative
Sumreduce(lambda...)sum()
Maxreduce(lambda...)max()
Minreduce(lambda...)min()
Concatenationreduce()''.join(), ' '.join()

Note

πŸ’‘ reduce() is powerful, but built-in functions are often clearer and faster.

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 πŸŽ‰

>>β€œreduce() condenses sequences into powerful single-value results β€” compact and functional.” ✨

You now fully understand Python’s reduce() function! Want the next topic? Try Recursion, Modules, Decorators, or OOP (Classes & Objects). Just tell me! 😊