Search code examples
pythonrange

How to find range overlap in python?


What is the best way in Python to determine what values in two ranges overlap?

For example:

x = range(1,10)
y = range(8,20)

(The answer I am looking for would be the integers 8 and 9.)
        

Given a range, x, what is the best way to iterate through another range, y and output all values that are shared by both ranges?

EDIT:

As a follow-up, I realized that I also need to know if x does or does not overlap y. I am looking for a way to iterate through a list of ranges and and do a number of additional things with range that overlap. Is there a simple True/False statement to accomplish this?


Solution

  • Try with set intersection:

    x = range(1,10)
    y = range(8,20)
    xs = set(x)
    xs.intersection(y)   
    

    Output:

    set([8, 9])
    

    Note that intersection accepts any iterable as an argument (y is not required to be converted to a set for the operation). There is an operator equivalent to the intersection method: & but, in this case, it requires both arguments to be sets.