Check If x is in Range – Python

Check If x is in Range

To check if given value (x) is present in the given range (series specified by the given Python range object), use in keyword 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.

Example 1: Check if x 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

Output

x is in the given range.

Example 2: Check if x 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

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.