Python – Check if Range contains specific element

Check if Range contains specific element in Python

To check if given value (x) is present in the given range (series specified by the given Python range object), use Python in membership operator in If-statement.

Code Snippet

The expression to check if x is present in the range(start, end) is

x in range(start, end)

This expression returns True if x is present in the range, or False if not.

Examples

1. Check if value 4 is in range (1, 8)

In this example, we take a range from 1 until 8(excluded), in steps of one (default step value), and check if value in x (=4) is present in this range.

Python Program

x = 4
if x in range(1, 8):
    print('x is in the given range.')
else:
    print('x is not in the given range.')
Run Code Copy

Output

x is in the given range.

2. Check if value 4 in range (1, 8, 2)

In this example, we take a range from 1 until 8(excluded), in steps of two, and check if value in x (=4) is present in this range.

Python Program

x = 4
if x in range(1, 8, 2):
    print('x is in the given range.')
else:
    print('x is not in the given range.')
Run Code Copy

Output

x is not in the given range.

Since the range(1, 8, 2) contains the series 1, 3, 5, 7, checking if x=4 is present in the range returns False.

Summary

In this tutorial of Python Examples, we learned how to check if a value is present is present in the series specified by a Python range object.

Code copied to clipboard successfully 👍