Quick Reference to map() function in Python
The map() function in Python takes a function and applies it to each item in a list or other collection, returning a new collection with the transformed items. It’s a handy way to perform operations across many elements without writing a loop.
How map() Works
The basic syntax of map() is:
map(function, iterable)
map() returns an iterator that you can turn into a list, tuple, or use in a loop.
Example 1: Using map() with a Function
Suppose you have a list of numbers, and you want to square each one.
def square(x):
return x ** 2
numbers = [1, 2, 3, 4]
squared = map(square, numbers) #Applies square() to each item in numbers print(list(squared)) #Output : [1, 4, 9, 16]
In this example:
Example 2: Using map() with a Lambda Function
Using a lambda function with map() makes it even shorter.
Recommended by LinkedIn
numbers = [1, 2, 3, 4]
squared = map(lambda x: x ** 2, numbers) #Same as above but shorter print(list(squared)) #Output: [1, 4, 9, 16]
Example 3: map() with Multiple Iterables
If you provide multiple lists, map() applies the function to items from each list in parallel.
list1 = [1, 2, 3]
list2 = [10, 20, 30]
sums = map(lambda x, y: x + y, list1, list2)
print(list(sums)) # Output: [11, 22, 33]
Here, the function lambda x, y: x + y takes one element from each list, adds them, and returns the result.
Key Points
Why Use map()?
It’s concise, readable, and often more efficient than a for loop, especially when working with large collections.
---
#Python #ProgrammingTips #Coding #DataScience #MachineLearning #MapFunctions #TechEducation #SoftwareEngineering