Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Mastering map Function | Higher-Order Functions and Lambdas
Functional Programming Concepts in Python
Seção 2. Capítulo 2
single

single

Mastering map Function

Deslize para mostrar o menu

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.

Tarefa

Deslize para começar a programar

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.

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 2
single

single

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

some-alt