Python
Range

Understanding the Range Data Type in Python

In Python, the range data type is used to represent a sequence of numbers. It provides a convenient way to generate a series of integers within a specified range. The range type is an immutable sequence, and it is often used with loops to iterate over a specific number of times. In this post, we will explore the range data type and learn how to use it effectively with code examples.

Creating a Range

You can create a range object using the range() function, which takes three arguments: start, stop, and step.

  • The start argument specifies the starting value of the range (inclusive),
  • the stop argument specifies the stopping value of the range (exclusive),
  • and the step argument specifies the increment between consecutive numbers (default is 1).

Here are some examples of creating ranges:

# Range from 0 to 9 (exclusive) with a step of 1
range1 = range(10)
print(list(range1))  # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
# Range from 1 to 10 (exclusive) with a step of 1
range2 = range(1, 11)
print(list(range2))  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
# Range from 0 to 10 (exclusive) with a step of 2
range3 = range(0, 11, 2)
print(list(range3))  # Output: [0, 2, 4, 6, 8, 10]

Using Range with Loops

One of the most common use cases of the range data type is to use it with loops for iterating over a sequence of numbers. This allows you to perform a set of actions repeatedly for a specified number of times. Here's an example of using range with a for loop:

# Looping through the range and printing the numbers
for num in range(5):
    print(num)

Output:

0
1
2
3
4

In this example, the for loop iterates over the range(5) object, which generates numbers from 0 to 4 (exclusive). The loop then prints each number on a separate line.

Range in Combination with len()

You can also use the range data type in combination with the len() function to create a loop that iterates over the indices of a sequence (e.g., a list or string). Here's an example:

fruits = ["apple", "banana", "cherry"]
 
# Looping through the list using range and len
for i in range(len(fruits)):
    print(fruits[i])

Output:

apple
banana
cherry

In this example, the range(len(fruits)) generates numbers from 0 to 2 (exclusive), which corresponds to the indices of the fruits list. The loop then prints each element of the list based on its index.