Tutorials  /  Python

Python map() function

Ccentron Redaktion · February 2024 ·4 min read ·Python, Tutorial

Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc. using their factory functions.

Python map() function

Python map() function syntax is:

Code
map(function, iterable, ...)

We can pass multiple iterable arguments to map() function, in that case, the specified function must have that many arguments. The function will be applied to these iterable elements in parallel. With multiple iterable arguments, the map iterator stops when the shortest iterable is exhausted.

VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Python map() example

Let’s write a function to be used with map() function.

Python
def to_upper_case(s):
    return str(s).upper()

It’s a simple function that returns the upper case string representation of the input object. I am also defining a utility function to print iterator elements. The function will print iterator elements with white space and will be reused in all the code snippets.

Python
def print_iterator(it):
    for x in it:
        print(x, end=' ')
    print('')  # for new line

Python map() with string

Python
map_iterator = map(to_upper_case, 'abc')
print(type(map_iterator))
print_iterator(map_iterator)

Output:

Code
<class 'map'>
A B C 

Python map() with tuple

Code
map_iterator = map(to_upper_case, (1, 'a', 'abc'))
print_iterator(map_iterator)

Output:

Code
1 A ABC 

Python map() with list

Code
map_iterator = map(to_upper_case, ['x', 'a', 'abc'])
print_iterator(map_iterator)

Output:

Code
X A ABC 

Converting map to list, tuple, set

Since map object is an iterator, we can pass it as an argument to the factory methods for creating a list, tuple, set etc.

Python
map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_list = list(map_iterator)
print(my_list)

map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_set = set(map_iterator)
print(my_set)

map_iterator = map(to_upper_case, ['a', 'b', 'c'])
my_tuple = tuple(map_iterator)
print(my_tuple)

Output:

Code
['A', 'B', 'C']
{'C', 'B', 'A'}
('A', 'B', 'C')

Python map() with lambda

We can use lambda functions with map() if we don’t want to reuse it. This is useful when our function is small and we don’t want to define a new function.

Code
list_numbers = [1, 2, 3, 4]

map_iterator = map(lambda x: x * 2, list_numbers)
print_iterator(map_iterator)

Output:

Code
2 4 6 8 

Python map() multiple arguments

Let’s look at an example of using map() function with multiple iterable arguments.

Code
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)

Output: 5 12 21 32 Notice that our function has two arguments. The output map iterator is the result of applying this function to the two iterable elements in parallel. Let’s see what happens when the iterables are of different sizes.

Code
list_numbers = [1, 2, 3, 4]
tuple_numbers = (5, 6, 7, 8, 9, 10)
map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers)
print_iterator(map_iterator)

map_iterator = map(lambda x, y: x * y, tuple_numbers, list_numbers)
print_iterator(map_iterator)

Output:

Code
5 12 21 32 
5 12 21 32 

So when the arguments are of different sizes, then the map function is applied to the elements until one of them is exhausted.

Python map() with function None

Let’s see what happens when we pass the function as None.

Python
map_iterator = map(None, 'abc')
print(map_iterator)
for x in map_iterator:
    print(x)

Output:

Code
Traceback (most recent call last):
  File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_map_example.py", line 3, in 
    for x in map_iterator:
TypeError: 'NoneType' object is not callable
Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren