What is range(len())

Introduction:

  • In Python, the len() function returns the number of elements in an iterable (like a list, tuple, or string). When used with range(), it generates a sequence of numbers from 0 to the length of the iterable minus one. This sequence can then be used as indices to access elements in the iterable.

How It Works:

  1. Using len() Function:
    • The len() function returns the number of elements in an iterable.
  2. Print Characters of a String:
    • Write a program to print each character of a string using range(len()).

      python
      my_string = "hello"
      for i in range(len(my_string)):
          print(my_string[i])
      
  3. Sum Elements of a List:
    • Write a program to sum the elements of a list using range(len()).

      python
      numbers = [10, 20, 30, 40]
      total = 0
      for i in range(len(numbers)):
          total += numbers[i]
      print(total)  # Output: 100
      

Summary:

  • In this tutorial, we learned what range(len()) means in Python and how to use it to iterate over the indices of a given iterable. This is a useful technique for accessing elements in an iterable by their index. Practice these examples to get comfortable with range(len()) in your Python programs!