List Manipulation
Common List Operations with Lambda
Lambda functions provide powerful and concise ways to manipulate lists in Python. This section explores various list operations using lambda functions.
Mapping with Lambda
The map()
function allows transforming list elements using lambda:
## Squaring numbers
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) ## Output: [1, 4, 9, 16, 25]
Filtering with Lambda
The filter()
function selects list elements based on a condition:
## Filtering even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) ## Output: [2, 4, 6, 8, 10]
Sorting with Lambda
Lambda can define custom sorting keys:
## Sorting complex data structures
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
## Sort by grade
sorted_students = sorted(students, key=lambda student: student['grade'])
print(sorted_students)
List Comprehension with Lambda
Combining list comprehensions with lambda for complex transformations:
## Advanced filtering and transformation
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = [x**2 for x in numbers if (lambda x: x % 2 == 0)(x)]
print(result) ## Output: [4, 16, 36, 64, 100]
Lambda Operations Workflow
graph TD
A[Original List] --> B[Lambda Function]
B --> C{Operation Type}
C -->|Map| D[Transformed List]
C -->|Filter| E[Filtered List]
C -->|Sort| F[Sorted List]
Operation |
Complexity |
Readability |
map() |
O(n) |
High |
filter() |
O(n) |
Moderate |
sorted() |
O(n log n) |
Moderate |
Best Practices
- Use lambda for simple, one-line transformations
- Prefer list comprehensions for more complex operations
- Consider readability over brevity
LabEx recommends practicing these techniques to master list manipulation with lambda functions.