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 withrange(), it generates a sequence of numbers from0to the length of the iterable minus one. This sequence can then be used as indices to access elements in the iterable.
How It Works:
- Using
len()Function:- The
len()function returns the number of elements in an iterable.
- The
- Print Characters of a String:
Write a program to print each character of a string using
range(len()).pythonmy_string = "hello" for i in range(len(my_string)): print(my_string[i])
- Sum Elements of a List:
Write a program to sum the elements of a list using
range(len()).pythonnumbers = [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 withrange(len())in your Python programs!