GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Python map Function - Complete Guide Python map FunctionLast modified April 11, 2025
This comprehensive guide explores Python's Basic Definitions
The Key characteristics: lazy evaluation (returns iterator), works with any callable, supports multiple iterables. The map object can be converted to other sequences like lists or tuples. Basic Numeric Transformation
Here's simple usage with numbers showing how basic_map.py
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squared = map(square, numbers)
print(list(squared)) # [1, 4, 9, 16, 25]
This example shows
Note that the original Using Lambda Functions
lambda_map.py
numbers = [1, 2, 3, 4, 5] doubled = map(lambda x: x * 2, numbers) print(list(doubled)) # [2, 4, 6, 8, 10] Here we use a lambda function to double each number. The lambda syntax is compact and avoids defining a separate named function for simple operations. This approach is particularly useful when the transformation logic is simple and won't be reused elsewhere in the code. Multiple Iterables
multi_map.py
def add(a, b):
return a + b
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
result = map(add, nums1, nums2)
print(list(result)) # [5, 7, 9]
This example adds corresponding elements from two lists. The
The resulting iterator stops when the shortest input iterable is exhausted.
This behavior is consistent with other Python functions like Type Conversion
type_map.py
str_numbers = ["1", "2", "3", "4"] int_numbers = map(int, str_numbers) print(list(int_numbers)) # [1, 2, 3, 4]
Here we use Python's built-in
Similar patterns work with other type constructors like Processing Text Data
This example shows how text_map.py
names = ["alice", "bob", "charlie"] capitalized = map(str.capitalize, names) print(list(capitalized)) # ["Alice", "Bob", "Charlie"]
We use the
This pattern works with any string method, making Best Practices
Source ReferencesAuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |