Python - Element Index in Range Tuples

Python - Element Index in Range Tuples

In this tutorial, we'll learn how to determine if an element's index is within a specified range given as tuples. Each tuple represents a start and end index.

Objective:

Given a list of elements and a list of index range tuples, determine for each element if its index is within any of the specified ranges.

Example:

Consider the list:

lst = ["a", "b", "c", "d", "e"] 

And the list of index range tuples:

ranges = [(1, 3), (4, 4)] 

The result should be:

[False, True, True, True, True] 

Approach:

  1. For each element in the list, determine its index.
  2. Check if the index falls within any of the given ranges.

Code:

def is_index_in_ranges(lst, ranges): result = [] for idx, ele in enumerate(lst): # Check if idx is in any range in_range = any(start <= idx <= end for start, end in ranges) result.append(in_range) return result lst = ["a", "b", "c", "d", "e"] ranges = [(1, 3), (4, 4)] print(is_index_in_ranges(lst, ranges)) 

Output:

[False, True, True, True, True] 

Explanation:

  • We iterate over the list with enumerate, which gives us both the index and the value of each element.

  • For each index, we use a generator expression with any to check if it falls within any of the specified ranges.

  • If the index of an element falls within any of the ranges, True is appended to the result list, otherwise False is appended.

Conclusion:

By combining the enumerate function with list comprehensions, we can efficiently determine whether the index of each element in a list falls within any given set of index ranges.


More Tags

ms-project android-viewpager2 sqldataadapter android-fileprovider filebeat ssh upload phpoffice control-statements latitude-longitude

More Programming Guides

Other Guides

More Programming Examples