Practical List Operations
Advanced List Manipulation Techniques
1. Filtering Lists
## Basic filtering
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) ## [2, 4, 6, 8, 10]
## Mapping elements
names = ['alice', 'bob', 'charlie']
capitalized_names = [name.capitalize() for name in names]
print(capitalized_names) ## ['Alice', 'Bob', 'Charlie']
List Operation Workflow
graph TD
A[Original List] --> B[Filter]
B --> C[Transform]
C --> D[Aggregate]
D --> E[Result List]
Common List Manipulation Methods
| Method |
Description |
Example |
filter() |
Selects elements based on condition |
filter(lambda x: x > 5, [1,2,3,4,5,6,7]) |
map() |
Transforms each element |
map(str.upper, ['a', 'b', 'c']) |
reduce() |
Aggregates list elements |
reduce(lambda x,y: x+y, [1,2,3,4]) |
3. List Sorting Techniques
## Complex sorting
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
## Sort by grade
sorted_students = sorted(students, key=lambda x: x['grade'], reverse=True)
print(sorted_students)
4. Nested List Operations
## Flattening nested lists
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [num for sublist in nested_list for num in sublist]
print(flattened) ## [1, 2, 3, 4, 5, 6]
graph TD
A[List Operations] --> B[List Comprehension]
A --> C[Built-in Functions]
A --> D[Generator Expressions]
B --> E[Fast and Readable]
C --> F[Efficient for Large Lists]
D --> G[Memory Efficient]
5. List Deduplication
## Remove duplicates
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers) ## [1, 2, 3, 4, 5]
Best Practices
- Use list comprehensions for readability
- Prefer built-in methods over manual loops
- Consider memory usage with large lists
- Choose appropriate data structures
Advanced Techniques
Combining Multiple Operations
## Complex list processing
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = (
[x ** 2 for x in data] ## Square numbers
if len(data) > 5 else ## Condition
[x for x in data] ## Original list
)
print(result)
By mastering these practical list operations, LabEx learners can write more efficient and elegant Python code, transforming complex data manipulation tasks into concise, readable solutions.