Practical Examples
## Converting strings to integers
str_numbers = ['1', '2', '3', '4', '5']
int_numbers = list(map(int, str_numbers))
print(int_numbers) ## Output: [1, 2, 3, 4, 5]
2. Multiple Iterable Mapping
## Performing operations on multiple lists
def multiply(x, y):
return x * y
list1 = [1, 2, 3]
list2 = [10, 20, 30]
result = list(map(multiply, list1, list2))
print(result) ## Output: [10, 40, 90]
3. String Manipulation
## Converting strings to uppercase
words = ['hello', 'world', 'python']
uppercase_words = list(map(str.upper, words))
print(uppercase_words) ## Output: ['HELLO', 'WORLD', 'PYTHON']
## Extracting specific attributes from objects
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
students = [
Student('Alice', 22),
Student('Bob', 25),
Student('Charlie', 20)
]
## Extract names
names = list(map(lambda student: student.name, students))
print(names) ## Output: ['Alice', 'Bob', 'Charlie']
5. Conditional Mapping
## Filtering and transforming simultaneously
def process_number(x):
return x * 2 if x > 0 else 0
numbers = [-1, 0, 1, 2, 3, -4]
processed = list(map(process_number, numbers))
print(processed) ## Output: [0, 0, 2, 4, 6, 0]
Mapping Workflow
graph LR
A[Input Data] --> B[map() Function]
B --> C{Transformation Logic}
C --> D[Transformed Output]
Practical Scenarios
Scenario |
Use Case |
Example |
Data Cleaning |
Convert data types |
String to Integer |
Data Processing |
Apply consistent transformations |
Uppercase conversion |
Object Manipulation |
Extract attributes |
Student name extraction |
map()
is generally faster than list comprehensions
- Suitable for large datasets
- Lazy evaluation saves memory
At LabEx, we emphasize practical skills in Python data manipulation techniques like map()
.