0
0
Pythonprogramming~5 mins

map() function in Python

Choose your learning style9 modes available
Introduction

The map() function helps you apply the same action to many items quickly without writing a loop.

You want to double every number in a list of prices.
You need to convert a list of strings to uppercase.
You want to add 10 to each score in a list of test results.
You want to change a list of temperatures from Celsius to Fahrenheit.
Syntax
Python
map(function, iterable, ...)

function is what you want to do to each item.

iterable is the list or group of items you want to change.

Examples
This doubles each number in the list.
Python
numbers = [1, 2, 3]
doubled = map(lambda x: x * 2, numbers)
print(list(doubled))
This changes each word to uppercase.
Python
words = ['cat', 'dog']
upper_words = map(str.upper, words)
print(list(upper_words))
This adds 5 to each number using a named function.
Python
def add_five(x):
    return x + 5

nums = [10, 20, 30]
result = map(add_five, nums)
print(list(result))
Sample Program

This program adds 3 to every number in the list and prints the new list.

Python
numbers = [1, 4, 7, 10]
# Use map to add 3 to each number
added_three = map(lambda x: x + 3, numbers)
# Convert map object to list to see results
print(list(added_three))
OutputSuccess
Important Notes

The map() function returns a special object called a map object. You often convert it to a list to see the results.

You can use a lambda (small anonymous function) or a named function with map().

If you use multiple iterables, map() applies the function to items from each iterable in order.

Summary

map() applies a function to every item in a list or group.

It helps avoid writing loops for simple repeated actions.

Remember to convert the result to a list to see the changed items.