A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://realpython.com/ref/builtin-functions/map/ below:

Python’s Built-in Functions – Real Python

The built-in map() function in Python allows you to apply a transformation function to each item of one or more iterables, producing an iterator that yields transformed items.

This function is particularly useful for processing and transforming data in a functional programming style without explicitly using a for loop. Here’s an example of using map() to square numbers in a list:

>>> numbers = [1, 2, 3, 4, 5]
>>> list(map(lambda x: x**2, numbers))
[1, 4, 9, 16, 25]
Copied! map() Signature
map(function, iterable, *iterables)
Copied! Arguments Argument Description function A callable that takes as many arguments as there are iterables. iterable An iterable such as a list, tuple, etc. *iterables Additional iterables of the same length as iterable. Return Value map() Examples

With built-in functions and a single iterable as arguments:

>>> list(map(float, ["12.3", "3.3", "-15.2"]))
[12.3, 3.3, -15.2]

>>> list(map(int, ["12", "3", "-15"]))
[12, 3, -15]
Copied!

With a custom function and a single iterable as arguments:

>>> def square(number):
...     return number ** 2
...

>>> numbers = [1, 2, 3, 4, 5]
>>> list(map(square, numbers))
[1, 4, 9, 16, 25]
Copied!

With a lambda function and a single iterable as arguments:

>>> list(map(lambda x: 2**x, [1, 2, 3, 4, 5, 6, 8]))
[2, 4, 8, 16, 32, 64, 256]
Copied!

With multiple iterables as arguments:

>>> first_it = [1, 2, 3]
>>> second_it = [4, 5, 6, 7]
>>> list(map(pow, first_it, second_it))
[1, 32, 729]
Copied! map() Common Use Cases

The most common use cases for the map() function include:

map() Real-World Example

Suppose you have a list of temperatures in Celsius, and you need to convert them into Fahrenheit. You can use map() to apply the conversion function across the entire list:

>>> def to_fahrenheit(celsius):
...     return round((9/5) * celsius + 32, 1)
...

>>> celsius = [0, 20, 37, 100]
>>> list(map(to_fahrenheit, celsius))
[32.0, 68.0, 98.6, 212.0]
Copied!

In this example, you use map() to convert a list of temperatures in Celsius into Fahrenheit by applying the to_fahrenheit() function to each item in the input list.

For additional information on related topics, take a look at the following resources:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4