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

single

Mastering map Function

Stryg for at vise menuen

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.

Opgave

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.

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 2
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

some-alt