Hi everyone,
I recently came across a scenario where I needed to iterate over a large range of numbers but completely exclude a specific sub-range in the middle (for example, looping from 1 to 100, but skipping 50 to 60).
Furthermore, a common extension of this problem is needing to exclude multiple, arbitrary sub-ranges at once (e.g., skipping 50..60, 75..80, etc.).
Currently, the idiomatic ways to solve this in Python are:
An explicit if/continue block:
Python
for i in range(1, 101):
if 50 <= i <= 60 or 75 <= i <= 80:
continue
# do something
Chaining multiple split ranges via itertools.chain:
Python
from itertools import chain
for i in chain(range(1, 50), range(61, 75), range(81, 101)):
# do something
Or using an inline list comprehension to filter dynamically:
Python
for i in [x for x in range(1, 101) if not (50 <= x <= 60 or 75 <= x <= 80)]:
# do something
While these approaches work , they quickly become hard to read, require precise mental math regarding the exclusive stop boundaries , or create unnecessary intermediate lists in memory just for filtering.
To improve expressiveness, I would love to propose a way to exclude one or multiple ranges. Taking inspiration from Pythonâs argument unpacking (*args), the feature could accept a variable amount of exclusion ranges:
Variant 1: A .skip() method on the range object (Backward-compatible)
This uses a *args style signature (def skip(self, *ranges)), allowing developers to pass as many exclusion ranges or tuples as they need without introducing a new keyword.
Python
# Proposed syntax with a single exclusion:
for i in range(1, 101).skip(range(50, 61)):
print(i)
# Proposed syntax with multiple exclusions (*args style):
for i in range(1, 101).skip(range(50, 61), range(75, 81)):
print(i)
Variant 2: A new skip operator/keyword (Syntactic Sugar)
An alternative would be an intuitive infix operator that accepts either a single range or a collection/tuple of ranges.
Python
# Proposed syntax:
for i in range(1, 101) skip (range(50, 61), range(75, 81)):
print(i)
I am aware that introducing a new keyword like skip comes with major backward-compatibility hurdles. However, the .skip(*ranges) method approach seems like a highly ergonomic, non-breaking addition to Pythonâs built-in range type.
What are your thoughts on extending range to natively support one or multiple exclusions? Has something similar been proposed or rejected in the past?
Thanks for your feedback!