The range data type is a built-in data type in Python that represents a sequence of numbers. It is commonly used when you need to iterate over a sequence of numbers in a for loop or when you want to generate a list of numbers without actually creating the entire list in memory.
Creating a Range
To create a range, you can use the built-in range() function. The range() function takes three arguments: start, stop, and step.
The start argument specifies the starting value of the range (inclusive), the stop argument specifies the ending value of the range (exclusive), and the step argument specifies the increment between each value. If omitted, the default values are start=0 and step=1.
Here’s an example that creates a range from 0 to 10:
my_range = range(0, 10)
print(list(my_range))
This will output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
You can also specify only the stop argument:
my_range = range(10)
print(list(my_range))
This will produce the same output as before. The start value is assumed to be zero if not explicitly specified.
Iterating over a Range
A common use case for ranges is iterating over them in a for loop. Since ranges represent sequences of numbers, they can be used as an iterable in loops.
To demonstrate this, let’s print all even numbers from 0 to 10:
for num in range(0, 10, 2):
print(num)
0
2
4
6
8
Range as a List
Although ranges are not actually lists, you can convert them into lists using the list() function. This can be useful if you need to manipulate the range as a list or if you want to see the values contained in the range.
Here’s an example that converts a range into a list and then prints it:
my_range = range(1, 6)
my_list = list(my_range)
print(my_list)
[1, 2, 3, 4, 5]
Conclusion
The range data type in Python is a powerful tool for working with sequences of numbers. It allows you to easily generate and iterate over ranges of values without having to create large lists in memory. By understanding how to create and use ranges effectively, you can simplify your code and make it more efficient.