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:

  1. 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.

      python
      myrange = range(0, 5)
      print(len(myrange))
      
    • Output: 5
       
  2. 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.

      python
      myrange = range(0, 20, 3)
      print(len(myrange))
      
    • Output: 7
       

Exercises:

  1. Finding Length of a Simple Range:
    • Create a range from 0 to 10 and find its length.

      python
      my_range = range(0, 11)
      print(len(my_range))
      
  2. Finding Length of a Range with Step:
    • Create a range from 5 to 50 with a step value of 5 and find its length.

      python
      my_range = range(5, 51, 5)
      print(len(my_range))
      
  3. Finding Length of a Negative Step Range:
    • Create a range from 20 to 0 with a step value of -2 and find its length.

      python
      my_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 the len() function to determine the number of items in various ranges in your Python programs!