w3resource

What is the purpose of Python's map function?

Using lambda functions in Python higher-order functions

Python's "map" function applies a specified function to each item in an iterable (e.g., list, tuple) and returns an iterator that contains the results. In this way, you can perform the same operation on all elements of a collection without looping explicitly. In functional programming, the "map" function provides a concise and expressive way to transform data elements.

The map function syntax is as follows:

map(function, iterable)

Arguments:

  • function: It is the function applied to each element of the iterable. It can be a built-in function, a lambda function, or a user-defined function.
  • iterable: It is the collection of items (e.g., list, tuple) on which the function will be applied.

Example: Using a Lambda Function

# Find the cube of each list element.
nums = [1, 2, 3, 4, 5]
cube_numbers = map(lambda x: x ** 3, nums)
print(list(cube_numbers))  # Output: [1, 8, 27, 64, 125]

In the above example, the lambda function lambda x: x ** 3 cubes each element of the 'nums' list, and the map function returns an iterator with the cube values. The list() function is used to convert the iterator to a list for easy printing.

Example: Using a Built-in Function

# Define a function to calculate the cube of a number
def cube(x):
    return x ** 3
# Create a list of numbers
numbers = [1, 2, 3, 4, 5]
# Apply the cube function to each number in the list using map()
cube_numbers = map(cube, numbers)
# Convert the iterator to a list to see the results
result = list(cube_numbers)
print(result)  

Output:

[1, 8, 27, 64, 125]


Follow us on Facebook and Twitter for latest update.