110 of 151 menu

The map function

The map function returns a modified iterable object after applying a given function to it. In the first parameter, we specify the callback function that will be applied to each element. In the second parameter, we specify the object to iterate over.

The function returns a special iterable object as its result. It can be converted to a list using the list function.

Syntax

map(function, object for filtering)

Example

Let's use the map function to square each element of our list:

lst = [2, 3, 6, 8, 15] res = map(lambda x: x ** 2, lst) print(list(res))

Result of code execution:

[4, 9, 36, 64, 225]

Example

Now let's apply the map function to the tuple and print the result as a list:

tlp = (2, 5, 7, 8) res = map(lambda x: x + x, tlp) print(list(res))

Result of code execution:

[4, 10, 14, 16]

See also

  • function filter,
    which filters iterable objects
  • function zip,
    which iterates over tuples
byenru