How to find range overlap in python?

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.


If the step is always +1 (which is the default for range) the following should be more efficient than converting each list to a set or iterating over either list:

range(max(x[0], y[0]), min(x[-1], y[-1])+1)

Tags:

Python

Range