Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

The Python map() Function with Examples

Apply a function to every item of a list or other iterable with map().

How-To Guides2 min read5 screenshots

How map() works

map() takes a function and one or more iterables. It applies the function to each item and returns a map object, a lazy iterator.

map(function, iterable1, iterable2, ...)

When you use several iterables, map() stops at the shortest one.

Convert a map object to a list

A map object does not show its values by itself. Convert it with list().

Example: square each item.

nums = [11, 22, 33, 44, 55]
squares = map(lambda x: x ** 2, nums)
convList = list(squares)
print(convList)
Squares of a list converted to a list

Output:

[121, 484, 1089, 1936, 3025]

Use map() with several iterables

inputList1 = [11, 22, 33]
inputList2 = [44, 55, 66]
resultList = map(lambda x, y: x + y, inputList1, inputList2)
print(list(resultList))
Using map with two lists

Output:

[55, 77, 99]

Get the first character of each string

employees = ['Anna', 'Omar', 'Karim', 'David']
firstLetters = map(lambda s: s[0], employees)
extractedChars = list(firstLetters)
print(extractedChars)
Extracting the first letters with map

Output:

['A', 'O', 'K', 'D']

Change letter case

names = ['anna', 'omar', 'karim']
upperNames = map(str.upper, names)
print(list(upperNames))
Converting the letters to upper case

Output:

['ANNA', 'OMAR', 'KARIM']

You can pass a built-in function like str.upper directly.

Convert Celsius to Fahrenheit

def to_fahrenheit(c):
    return (c * 9 / 5) + 32

celsius = [0, 20, 37, 100]
fahrenheit = map(to_fahrenheit, celsius)
print(list(fahrenheit))
Converting temperatures with map

Output:

[32.0, 68.0, 98.6, 212.0]

map() or a list comprehension

A list comprehension often reads better:

squares = [x ** 2 for x in nums]

Use map() when you already have a named function, or when you want a lazy iterator that does not build the whole list at once.

Quick recap

  • map(func, iterable) returns a lazy iterator, so wrap it in list() to see values.