🚀 Day 96/150 – map() Function in Python
The map() function is a built-in Python function used to apply a function to every item in an iterable, such as a list or tuple. It helps you write cleaner and more concise code by avoiding explicit loops.
Syntax:
map(function, iterable)In this post, we'll explore four common examples of using the map() function in Python.
Method 1 – Using map() with a Normal Function
Apply a normal function to every element in a list.
def square(num): return num ** 2 numbers = [1, 2, 3, 4, 5] result = list(map(square, numbers)) print(result)
Output
[1, 4, 9, 16, 25]Explanation
- square() returns the square of a number.
- map() applies the square() function to every element in numbers.
- list() converts the map object into a list.
Method 2 – Using map() with a Lambda Function
Use a lambda function for shorter code.
numbers = [2, 4, 6, 8] result = list(map(lambda x: x * 2, numbers)) print(result)
Output
[4, 8, 12, 16]Explanation
- lambda x: x * 2 doubles each element.
- map() applies the lambda function to every item in the list.
- The result is converted into a list.
Method 3 – Using map() with Multiple Iterables
map() can process multiple iterables at the same time.
list1 = [1, 2, 3] list2 = [4, 5, 6] result = list(map(lambda x, y: x + y, list1, list2)) print(result)
Output
[5, 7, 9]Explanation
- map() takes one element from each list at the same position.
- The lambda function adds the corresponding elements.
- The result is returned as a new list.
Method 4 – Taking User Input
Use map() to convert multiple user inputs into integers.
numbers = list(map(int, input("Enter numbers separated by spaces: ").split())) print(numbers)
Sample Input
10 20 30 40Output
[10, 20, 30, 40]Explanation
- input() reads the values as a string.
- split() separates the string into a list of strings.
- map(int, ...) converts each string into an integer.
- list() stores the converted values in a list.
Comparison of Methods
| Method | Best For |
|---|---|
| Normal Function | Reusing existing functions |
| Lambda Function | Short and simple operations |
| Multiple Iterables | Processing two or more lists together |
| User Input | Converting input values to the desired data type |
🔥 Key Takeaways
- map() applies a function to every element in an iterable.
- It returns a map object, which is often converted to a list using list().
- map() works with both normal functions and lambda functions.
- It can process multiple iterables simultaneously.
- map() makes code cleaner and often replaces explicit for loops for simple transformations.
%20Function%20in%20Python.png)
