0
0
Pythonprogramming~5 mins

Lambda with map() in Python

Choose your learning style9 modes available
Introduction

Lambda with map() helps you quickly change all items in a list without writing a full function. It makes your code shorter and easier to read.

You want to add 1 to every number in a list.
You need to turn all words in a list to uppercase.
You want to get the length of each string in a list.
You want to square each number in a list.
You want to convert a list of temperatures from Celsius to Fahrenheit.
Syntax
Python
map(lambda item: expression, iterable)

lambda item: This is a small function that takes one input called item.

iterable: This is the list or collection you want to change.

Examples
This example squares each number in the list.
Python
numbers = [1, 2, 3]
squared = map(lambda x: x * x, numbers)
print(list(squared))
This example changes all words to uppercase.
Python
words = ['cat', 'dog']
upper_words = map(lambda w: w.upper(), words)
print(list(upper_words))
This example converts Celsius temperatures to Fahrenheit.
Python
temps_c = [0, 10, 20]
temps_f = map(lambda c: (c * 9/5) + 32, temps_c)
print(list(temps_f))
Sample Program

This program takes a list of numbers and uses lambda with map() to square each number. Then it prints the new list.

Python
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x * x, numbers)
print(list(squared_numbers))
OutputSuccess
Important Notes

Remember to convert the result of map() to a list to see all items at once.

Lambda functions are small and quick, but if your logic is complex, use a normal function instead.

Summary

Use lambda with map() to quickly change all items in a list.

map() applies the lambda function to each item in the list.

Convert the result of map() to a list to see the output.