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)        

  • function: The function you want to apply to each item.
  • iterable: The list, tuple, or other collection you’re applying the function to.

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:

  1. square is applied to each number in numbers.
  2. map collects all the results into an iterator.
  3. We convert it to a list to see [1, 4, 9, 16].

Example 2: Using map() with a Lambda Function

Using a lambda function with map() makes it even shorter.

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

  • map() saves time by avoiding loops.
  • You can use it with regular functions or lambda functions.
  • You can combine multiple lists, applying the function to items in parallel.

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


To view or add a comment, sign in

More articles by Aniruddha Pal

Insights from the community

Others also viewed

Explore topics