Filtering Lists
Using filter() Function
The filter()
function allows selective transformation by removing elements that don't meet specific conditions.
## 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]
Sorted() and sort() Methods
Python provides multiple ways to sort list elements.
## Sorting in ascending and descending order
original_list = [3, 1, 4, 1, 5, 9, 2]
sorted_ascending = sorted(original_list)
sorted_descending = sorted(original_list, reverse=True)
print(sorted_ascending) ## Output: [1, 1, 2, 3, 4, 5, 9]
print(sorted_descending) ## Output: [9, 5, 4, 3, 2, 1, 1]
Lambda Functions
Lambda functions enable quick, inline transformations.
## Complex transformation using lambda
data = [{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30},
{'name': 'Charlie', 'age': 35}]
names = list(map(lambda x: x['name'], data))
print(names) ## Output: ['Alice', 'Bob', 'Charlie']
graph TD
A[Original List] --> B{Transformation Method}
B --> |Filter| C[Filtered List]
B --> |Map| D[Mapped List]
B --> |Sort| E[Sorted List]
Method |
Use Case |
Performance |
Complexity |
filter() |
Selective Filtering |
High |
Low |
map() |
Element-wise Transformation |
High |
Low |
sorted() |
Ordering Elements |
Moderate |
Moderate |
List Comprehension |
Flexible Transformation |
High |
Low |
LabEx Pro Tip
At LabEx, we recommend mastering these transformation methods to write more concise and efficient Python code.
Best Practices
- Choose the most appropriate transformation method
- Consider performance for large datasets
- Prioritize code readability
- Use lambda functions for simple, inline transformations