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

single

Mastering map Function

Svep för att visa menyn

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)

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.

Uppgift

Svep för att börja koda

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.

Lösning

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 2
single

single

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt