Search notes:

Python: map

map can be used to apply a function to each element in a list. It's probably the closest equivalent to the equally named Perl function.

Square numbers

The following snippet uses a lambda expression to square the numbers in a list:
#!/usr/bin/python

nums    = [4, 9, 5, 2, 8]

#
#   Apply a lambda expression on each element of nums
#   to calculate the square of the number and return
#   the number and its square in a tuple:
#
for squared in map(lambda num: (num, num*num), nums):
    print(' {:d}^2 = {:2d}'.format(squared[0], squared[1]))
Github repository about-Python, path: /builtin-functions/map/square-items.py

See also

The functionality of map can often (always) be achieved with a list comprehension.
Python: Built in functions
Using map to convert numpy arrays to torch tensors
Common first class function: map

Index