Extending List Operations
Advanced List Manipulation Techniques
List Comprehensions
List comprehensions provide a concise way to create lists based on existing lists:
## Basic list comprehension
squares = [x**2 for x in range(10)]
print(squares) ## Outputs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
## Conditional list comprehension
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) ## Outputs: [0, 4, 16, 36, 64]
List Concatenation and Multiplication
## Concatenating lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) ## Outputs: [1, 2, 3, 4, 5, 6]
## Repeating lists
repeated_list = list1 * 3
print(repeated_list) ## Outputs: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Advanced List Methods
Method |
Description |
Example |
extend() |
Adds all elements from another list |
list1.extend([4, 5]) |
pop() |
Removes and returns last element |
last_item = list1.pop() |
sort() |
Sorts list in-place |
list1.sort() |
reverse() |
Reverses list in-place |
list1.reverse() |
Nested Lists and Deep Operations
## Nested lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
## Accessing nested elements
print(matrix[1][1]) ## Outputs: 5
## Flattening nested lists
flattened = [num for row in matrix for num in row]
print(flattened) ## Outputs: [1, 2, 3, 4, 5, 6, 7, 8, 9]
List Operation Flow
graph TD
A[Original List] --> B{Operation}
B -->|Comprehension| C[New Transformed List]
B -->|Concatenation| D[Combined List]
B -->|Manipulation| E[Modified List]
Advanced Filtering and Mapping
## Filtering with lambda
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered = list(filter(lambda x: x % 2 == 0, numbers))
print(filtered) ## Outputs: [2, 4, 6, 8, 10]
## Mapping with lambda
mapped = list(map(lambda x: x**2, numbers))
print(mapped) ## Outputs: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
When working with lists in LabEx programming environments, be mindful of:
- Memory usage
- Time complexity of operations
- Choosing appropriate methods for specific tasks
By mastering these extended list operations, you'll become more efficient in Python data manipulation.