Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Extract elements from Ranges in List
When working with lists, you often need to extract elements from specific index ranges. Python provides several approaches to accomplish this task efficiently using slicing and list methods.
Understanding Range Extraction
Range extraction involves taking elements from a list based on start and end positions defined in tuples. Each tuple contains two values: the start index and the end index.
Using extend() Method
The extend() method adds all elements from a slice to the result list ?
my_list = [14, 55, 41, 14, 17, 59, 22, 25, 14, 69, 42, 66, 99, 19]
print("The original list is:")
print(my_list)
range_list = [(1, 3), (5, 7), (12, 13)]
print("The ranges are:")
print(range_list)
my_result = []
for start, end in range_list:
my_result.extend(my_list[start:end + 1])
print("The extracted elements are:")
print(my_result)
The original list is: [14, 55, 41, 14, 17, 59, 22, 25, 14, 69, 42, 66, 99, 19] The ranges are: [(1, 3), (5, 7), (12, 13)] The extracted elements are: [55, 41, 14, 59, 22, 25, 99, 19]
Using List Comprehension
A more concise approach uses list comprehension with nested loops ?
my_list = [14, 55, 41, 14, 17, 59, 22, 25, 14, 69, 42, 66, 99, 19]
range_list = [(1, 3), (5, 7), (12, 13)]
result = [my_list[i] for start, end in range_list for i in range(start, end + 1)]
print("Extracted elements:")
print(result)
Extracted elements: [55, 41, 14, 59, 22, 25, 99, 19]
Using itertools.chain
For better performance with large datasets, use itertools.chain ?
import itertools
my_list = [14, 55, 41, 14, 17, 59, 22, 25, 14, 69, 42, 66, 99, 19]
range_list = [(1, 3), (5, 7), (12, 13)]
result = list(itertools.chain.from_iterable(my_list[start:end + 1] for start, end in range_list))
print("Extracted elements:")
print(result)
Extracted elements: [55, 41, 14, 59, 22, 25, 99, 19]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
extend() |
High | Good | Learning and clarity |
| List comprehension | Medium | Better | Concise code |
itertools.chain |
Medium | Best | Large datasets |
Conclusion
Use extend() for clear, readable code when extracting elements from ranges. For performance-critical applications, consider itertools.chain or list comprehension approaches.
