Advanced list extraction goes beyond basic slicing, offering sophisticated methods to manipulate and extract data with precision and efficiency.
## Extracting from nested lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
## Extract specific nested elements
diagonal = [matrix[i][i] for i in range(len(matrix))]
print(diagonal) ## Output: [1, 5, 9]
## Extract elements based on complex conditions
data = [10, 15, 20, 25, 30, 35, 40]
filtered_data = [x for x in data if x > 20 and x % 2 == 0]
print(filtered_data) ## Output: [30, 40]
graph TD
A[Original List] --> B[Extraction Criteria]
B --> C{Condition Check}
C -->|Pass| D[Select Element]
C -->|Fail| E[Skip Element]
D --> F[New List]
Advanced Slicing Techniques
## Multi-dimensional list extraction
complex_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
## Extract specific columns
columns = list(zip(*complex_list))
print(columns) ## Output: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Method |
Use Case |
Performance |
Complexity |
List Comprehension |
Conditional Extraction |
High |
Medium |
filter() |
Functional Extraction |
Medium |
Low |
Generator Expressions |
Memory Efficient |
High |
Medium |
## Generator-based extraction
def extract_large_data(data):
return (x for x in data if x % 2 == 0)
large_list = range(1000000)
even_generator = extract_large_data(large_list)
Advanced Slicing Techniques
## Slice with custom step and complex conditions
def smart_extract(lst, start=None, end=None, step=1, condition=None):
return [x for x in lst[start:end:step] if condition is None or condition(x)]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = smart_extract(numbers, start=2, end=8, step=2, condition=lambda x: x > 4)
print(result) ## Output: [6, 8]
Key Takeaways
- Advanced extraction requires understanding of list comprehensions
- Conditional extraction provides powerful filtering
- Consider memory efficiency for large datasets
LabEx encourages exploring these advanced techniques to master Python list manipulation.