7. Membership Testing & Finding the Length of a Range

Membership Testing

You can check whether a number exists in a range using the in operator.

Example:

r = range(0, 10, 2)

print(6 in r)
print(7 in r)

Output:

True
False

Explanation:

  • 6 is in the range.

  • 7 is not in the range because the numbers increase by 2.

Finding the Length of a Range

Use the len() function to determine how many values are in a range.

Example:

r = range(0, 10, 2)

print(len(r))

Output:

5

The range contains:

0
2
4
6
8

So the length is 5.