map() – Transforming Data in a List

The map() function in Python is used to apply a given function to each item of an iterable (such as a list) and return a map object (an iterator). This function is particularly useful for transforming data in a list without explicitly writing a loop. You can pass any function and an iterable to map(), making it a powerful tool for functional programming in Python.

Code Example

# Define a function to square a number
def square(x):
    return x * x

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Use map() to apply the square function to each element in the list
squared_numbers = map(square, numbers)

# Convert the map object to a list to see the result
squared_numbers_list = list(squared_numbers)

# Print the resulting list of squared numbers
print(f"Squared numbers: {squared_numbers_list}")

Code Explanation

Defining a Function

First, a function square is defined that takes a single argument and returns its square.

def square(x):
    return x * x

Using the map() Function

The map() function is used to apply the square function to each element in the numbers list. The result is a map object, which is an iterator.

squared_numbers = map(square, numbers)

Converting the Map Object to a List

To see the result of the map() function, the map object is converted to a list. This is done using the list() function.

squared_numbers_list = list(squared_numbers)

Printing the Result

Finally, the resulting list of squared numbers is printed.

print(f"Squared numbers: {squared_numbers_list}")