Find length of a Range
Introduction:
- To find the length of a range in Python, you can use the
len()built-in function. This function returns an integer representing the number of items in the range.
Examples:
- Length of a Range with Start and Stop:
In this program, we define a range with specific start and stop values. Then we use the
len()function to get the length of this range object.pythonmyrange = range(0, 5) print(len(myrange))- Output:
5
- Length of a Range with a Step Value:
In this program, we find the length of a range object defined with specific start, stop, and step values.
pythonmyrange = range(0, 20, 3) print(len(myrange))- Output:
7
Exercises:
- Finding Length of a Simple Range:
Create a range from 0 to 10 and find its length.
pythonmy_range = range(0, 11) print(len(my_range))
- Finding Length of a Range with Step:
Create a range from 5 to 50 with a step value of 5 and find its length.
pythonmy_range = range(5, 51, 5) print(len(my_range))
- Finding Length of a Negative Step Range:
Create a range from 20 to 0 with a step value of -2 and find its length.
pythonmy_range = range(20, -1, -2) print(len(my_range))
Summary:
- In this tutorial, we learned how to find the length of a given range using the
len()built-in function. Practice using thelen()function to determine the number of items in various ranges in your Python programs!