List Manipulation
Advanced List Modification Techniques
Sorting Lists
## Basic sorting
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort() ## Ascending order
print(numbers) ## [1, 1, 2, 3, 4, 5, 9]
## Descending order
numbers.sort(reverse=True)
print(numbers) ## [9, 5, 4, 3, 2, 1, 1]
## Sorting with key function
words = ['python', 'java', 'javascript', 'c++']
words.sort(key=len) ## Sort by word length
print(words) ## ['c++', 'java', 'python', 'javascript']
graph TD
A[List Transformation] --> B[Reverse]
A --> C[Extend]
A --> D[Copy]
A --> E[Clear]
Reversing Lists
## In-place reversal
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) ## [5, 4, 3, 2, 1]
## Using reversed() function
numbers = [1, 2, 3, 4, 5]
reversed_numbers = list(reversed(numbers))
print(reversed_numbers) ## [5, 4, 3, 2, 1]
List Concatenation and Extension
## Concatenating lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) ## [1, 2, 3, 4, 5, 6]
## Extending lists
list1.extend(list2)
print(list1) ## [1, 2, 3, 4, 5, 6]
Advanced Manipulation Techniques
Filtering Lists
## Using filter() function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) ## [2, 4, 6, 8, 10]
Mapping Lists
## Using map() function
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) ## [1, 4, 9, 16, 25]
List Manipulation Techniques Comparison
Technique |
Method |
Performance |
Use Case |
Sorting |
sort() |
In-place |
Ordering elements |
Filtering |
filter() |
Creates new list |
Conditional selection |
Mapping |
map() |
Transforms elements |
Element-wise operations |
Copying Lists
## Shallow copy
original = [1, 2, 3]
shallow_copy = original.copy()
## Deep copy
import copy
deep_copy = copy.deepcopy(original)
- Use list comprehensions for better performance
- Avoid repeated list modifications
- Choose appropriate methods based on use case
LabEx recommends practicing these techniques to become proficient in list manipulation.