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

single

Mastering map Function

Veeg om het menu te tonen

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.

Taak

Veeg om te beginnen met coderen

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.

Oplossing

Switch to desktopSchakel over naar desktop voor praktijkervaringGa verder vanaf waar je bent met een van de onderstaande opties
Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 2
single

single

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

some-alt