Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Mastering map Function | Higher-Order Functions and Lambdas
Functional Programming Concepts in Python
Section 2. Chapter 2
single

single

bookMastering map Function

Swipe to show menu

The map Function in Python

The built-in map function is a classic example of a higher-order function. It takes two arguments: a function and an iterable (such as a list). map applies the given function to each item in the iterable and returns a map object, which is an iterator. You can convert this object to a list to see the results. This approach is useful for transforming data efficiently without writing explicit loops.

You can use map with a named function like double to process a list of numbers: map(double, [1, 2, 3, 4]) returns a map object that contains the doubled values. By converting the result to a list, you get [2, 4, 6, 8]. This demonstrates how map acts as a higher-order function by taking another function as its argument and applying it to each element of the iterable.

123456
def square(x): return x * x numbers = [1, 2, 3, 4, 5] squared_numbers = list(map(square, numbers)) print(squared_numbers)
copy

In this example, the square function is applied to each element in the numbers list. The result is a new list containing the squares of the original numbers. Notice how you did not need to write a loop — the map function handled the iteration for you.

You can also use map with built-in functions or even with anonymous functions (lambdas), which will be covered in upcoming chapters. For now, focus on how passing a function as an argument allows for flexible and reusable code transformations.

Task

Swipe to start coding

Write a function that takes a function and a list, and returns a new list with the function applied to each element.

  • The function must apply the provided function to every item in the provided list.
  • The function must return a new list containing the results.
  • Do not forget to remove pass.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 2
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt