Sling Academy
Home/Python/Range Type in Python: The Ultimate Guide (with Examples)

Range Type in Python: The Ultimate Guide (with Examples)

Last updated: February 13, 2024

Introduction

Understanding the range type in Python is crucial for implementing loops and understanding iterable objects. This comprehensive guide will take you through the basics of the range function, explore various examples demonstrating its utility, and gradually introduce more advanced techniques. Whether you’re new to programming or looking to deepen your understanding of Python iterables, this tutorial has something for everyone.

The Basics of Range in Python

The range() function in Python is used to generate a sequence of numbers. It is often used in for-loops to iterate over a sequence of numbers. Its basic syntax is range(start, stop, step), where:

  • start is the starting number of the sequence. This parameter is optional, and its default value is 0.
  • stop is the endpoint of the sequence. This number is not included in the sequence.
  • step is the difference between each number in the sequence. This parameter is optional, and its default value is 1.

Basic Examples of the Range Function

Let’s start with the most basic usage:

for i in range(5):
    print(i)

This will output:

0
1
2
3
4

Here, we didn’t specify the start or step, so Python defaults to 0 for start and 1 for step. The sequence runs up to, but does not include, the stop value, which in this case is 5.

Specifying Start, Stop, and Step

You can also specify all three arguments for more control:

for i in range(2, 10, 2):
    print(i)

Output:

2
4
6
8

This time, we specified a start of 2, a stop of 10, and a step of 2, generating a sequence of even numbers starting from 2.

Using Range with Conditional Statements

Range becomes particularly powerful when used in conjunction with conditional statements to perform more complex operations:

for i in range(10):
    if i % 2 == 0:
        print(f'{i} is even')
    else:
        print(f'{i} is odd')

This will output each number from 0 to 9, labelling it as even or odd.

Advanced Uses of Range

As we progress, let’s dive into more complex uses of range in Python.

Generating Negative Sequences

Using a negative step, we can generate a descending sequence:

for i in range(0, -10, -1):
    print(i)

Output:

-1
-2
-3
-4
-5
-6
-7
-8
-9

This can be particularly useful in loops where decrementing is needed.

Using Range with List Comprehensions

List comprehensions offer a concise way to create lists. The range function fits seamlessly into this:

[i for i in range(5)]

Output:

[0, 1, 2, 3, 4]

This generates a list containing numbers 0 through 4.

Iterating Over Indices in a List

Another advanced technique involves using range to iterate over the indices of a list:

my_list = ['apple', 'banana', 'cherry']
for i in range(len(my_list)):
    print(f'Item {i} is {my_list[i]}')

Output:

Item 0 is apple
Item 1 is banana
Item 2 is cherry

This method is especially useful when you need to access both the index and the value of list items.

Conclusion

Throughout this guide, we’ve explored the range type in Python from its most basic use cases to more advanced applications. Understanding how to use range effectively will not only help you write more concise and readable loops but also give you a deeper insight into iterable objects in Python. Experiment with the examples provided and incorporate range into your next Python project to see its versatility in action.

Next Article: Python: Checking if 2 ranges overlap (4 examples)

Previous Article: 5 ways to create a tuple in Python

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots