In Pythonmap()
A function is a built-in function that maps the specified sequence based on the provided functions.
Function definition
map()
The basic syntax of a function is as follows:
map(function, iterable, ...)
-
function
: A function,map()
Will beiterable
Each item in it is passed to this function. -
iterable
: One or more sequences,map()
It will be iterated.
map()
The function returns an iterator, which is generated byfunction
Applied toiterable
The result of each item.
Basic usage
Single sequence
def square(number): return number ** 2 numbers = [1, 2, 3, 4, 5] squared = map(square, numbers) print(list(squared)) # Output: [1, 4, 9, 16, 25]
Multiple sequences
def add(a, b): return a + b nums1 = [1, 2, 3] nums2 = [4, 5, 6] result = map(add, nums1, nums2) print(list(result)) # Output: [5, 7, 9]
Advanced Usage
Combined with lambda functions
map()
Often with anonymous functionslambda
Use together to create clean code.
numbers = [1, 2, 3, 4, 5] squared = map(lambda x: x ** 2, numbers) print(list(squared)) # Output: [1, 4, 9, 16, 25]
Using multiple iterators
You can pass multiple iterators tomap()
, functions will take values from these iterators in parallel.
a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] result = map(lambda x, y, z: x + y + z, a, b, c) print(list(result)) # Output: [12, 15, 18]
Things to note
- if
function
GivenNone
,map()
Will return directlyiterable
elements in. - if
iterable
The lengths are different,map()
Will stop at the end of the shortest sequence.
in conclusion
map()
It is a very useful built-in function in Python, which provides a convenient way to convert and manipulate elements in a sequence. Through the above routine, we can seemap()
Applications in real programming and how to use it effectively to simplify code and improve efficiency.
This is all about this article about the built-in Python function map(). For more related Python map() content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!