How to Use "for i in range()" in Python (With Clear Examples)

By

Liz Fujiwara

Aug 14, 2025

Need to loop through numbers in Python? The for i in range loop is your go-to method for iterating efficiently and cleanly. Python’s built-in range() function provides a versatile way to generate sequences of numbers, enabling you to control the start, stop, and step size of your loops. Whether you’re running a simple loop from zero up to a limit or creating more complex sequences, mastering for i in range is essential for writing concise and effective Python code. In this article, we’ll explore the different forms and parameters of the range() function, walk through practical examples, and share tips to help you use loops to improve your coding efficiency and clarity.

Key Takeaways

  • The range() function in Python is versatile and can be initialized with one, two, or three parameters, allowing users to define start, stop, and step values for generating numerical sequences.

  • The for i in range() loop enables repeated execution of code blocks a specific number of times and can be customized to start and stop at defined points or iterate with a specified step value.

  • Advanced techniques, such as using enumerate() and zip() with for i in range(), enhance iteration capabilities by allowing simultaneous processing of data from multiple sources and access to indices alongside values.

Understanding the Python range() Function

An illustration of the Python range function showcasing its parameters and usage.

The range() function in Python is designed to construct numerical ranges, which are indispensable for looping operations. It generates a sequence of numbers within a specified range, allowing you to control the starting point, ending point, and the difference between consecutive numbers. The flexibility of the range() function allows it to be initialized in three different ways, making it suitable for various scenarios. Understanding these different forms and how to utilize them is the first step toward harnessing the full potential of range in your Python programs.

Syntax and Parameters

The syntax for the range() function is range(start, stop, step), where start, stop, and step are the parameters that define the sequence. The function can be invoked with one, two, or three arguments. The required parameter is stop, which defines the end of the sequence (exclusive), while start and step are optional. By default, start is set to 0, and step is set to 1, creating a sequence that increments by 1. If start and stop are equal, the resulting range will be empty. The step parameter allows for custom increments or decrements, providing control over the sequence’s progression.

For example, range(0, 10, 2) generates the sequence [0, 2, 4, 6, 8], where the sequence starts at 0, ends before 10, and increments by 2. On the other hand, range(10, 0, -2) creates a descending sequence [10, 8, 6, 4, 2], where the sequence starts at 10, ends before 0, and decrements by 2.

Understanding these parameters and how they interact is crucial for effectively using the range() function in your Python code.

One-Parameter Form

When the range() function is called with a single argument, it generates a sequence starting from 0 up to, but not including, the specified number. For instance, range(5) produces the sequence [0, 1, 2, 3, 4]. It includes the numbers from zero to four. This form is ideal for executing a block of code a specific number of times.

For example, a basic For loop using this form of range can be written as:

for i in range(5):

which will iterate five times, with i taking values from 0 to 4.

Two-Parameter Form

Using two parameters in the range() function allows you to specify both the starting and stopping points of the sequence. For example, range(2, 7) generates the sequence [2, 3, 4, 5, 6], starting at 2 and ending before 7. This form offers more flexibility than the one-parameter version, letting you define both the start and end of the sequence.

Three-Parameter Form

The three-parameter form of the range() function introduces the step parameter, allowing you to control the increment or decrement between each value in the sequence. For example, range(0, 10, 2) generates the sequence [0, 2, 4, 6, 8], where the sequence starts at 0, ends before 10, and increments by 2. This form is especially useful for creating sequences with custom intervals.

When the step parameter is negative, the range function generates a descending sequence. For instance, range(10, 0, -1) creates the sequence [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], starting at 10 and decrementing by 1 until it reaches 1. This flexibility makes the three-parameter form invaluable for tasks requiring non-standard sequences or countdowns.

Using the for i in range() Loop in Python

A flowchart demonstrating the for i in range() loop in Python.

The for i in range() loop is a powerful construct in Python, allowing you to repeat specific tasks a defined number of times. It leverages the sequences generated by the range() function to control the iteration process.

This loop can be used to index into collections such as strings, lists, or tuples, making it a versatile tool for various programming tasks. Whether you’re running a block of code multiple times or manipulating elements within a collection, the for i in range() loop provides a structured and efficient approach to looping in Python.

Basic Looping with for i in range()

The most common use of the for i in range() loop is to repeat a block of code a set number of times. For example, for i in range(5): iterates five times, executing the block of code within the loop for each value of i from 0 to 4. This loop is particularly useful for tasks such as summing numbers, printing messages, or performing calculations multiple times.

Additionally, using len() with range() allows you to iterate through the indices of lists and tuples, enabling access to both values and their positions.

Looping with Custom Start and Stop Values

Custom start and stop values in the range() function allow for greater control over the iteration process. For instance, range(3, 8) starts the sequence at 3 and ends just before 8, resulting in [3, 4, 5, 6, 7]. This flexibility is useful for scenarios where you need to begin counting from a non-zero value or stop at a specific point.

Customizing the range function in this way enables more precise and flexible control over your loops.

Using Step Values in for Loops

The step parameter in the range() function allows you to define increments or decrements in the loop variable. For example, range(0, 10, 2) iterates with a step value of 2, generating the sequence [0, 2, 4, 6, 8]. This capability is particularly useful for creating countdowns or iterating over every nth element in a sequence.

Practical Examples of for i in range()

Examples of practical applications using the for i in range() loop in Python.

The for i in range() construct is widely utilized in Python for practical programming tasks, making code more efficient and readable. This section will explore several real-world examples to illustrate the versatility and power of this loop.

From generating multiplication tables to iterating over lists and tuples, these examples will demonstrate how for i in range() can simplify and enhance your Python code.

Generating Multiplication Tables

Generating multiplication tables is a classic use case for the for i in range() loop. By iterating through values from 1 to 10, you can create a multiplication table for any number. For example, to generate a multiplication table for 5, you could:

  • Use a for loop to iterate through numbers 1 to 10.

  • For each iteration, multiply 5 by the current number.

  • Print the result in the format “5 x i = result”.

Example code:

for i in range(1, 11): 

    print(f"5 x {i} = {5*i}")

multiplies 5 by each value of i and prints the result. This simple yet powerful example highlights the utility of the range function in performing repetitive calculations.

Iterating Over Lists and Tuples

The for i in range() loop is a common way to iterate through a sequence of numbers, which can be used to access elements in lists and tuples by their indices. For example, for i in range(len(my_list)): iterates through each index of my_list, allowing you to manipulate or print each element by its position. This approach is particularly useful for tasks that require modifying elements based on their index or performing operations that depend on the position within the sequence.

In addition to iterating over number sequences, the for i in range() loop can be effectively used to access elements by their indices for lists and tuples, enhancing its versatility.

While direct iteration over sequences is often simpler and more Pythonic, using for i in range() provides structured control and is especially useful for more complex operations that involve both the index and the value of each element.

Creating Nested Loops

Nested loops allow for the iteration of multiple sequences, enabling the programmer to tackle complex problems involving multi-dimensional data structures. For example, creating a simple grid pattern can be achieved by using nested for i in range() loops, where the outer loop controls the rows and the inner loop controls the columns. This technique is particularly useful for tasks such as generating matrices or printing shapes in a specific format.

Mastering nested loops enhances a programmer’s ability to create complex algorithms and solve challenging tasks efficiently. By combining multiple range() functions, you can iterate over different dimensions of a data structure, allowing for sophisticated operations and pattern generation.

Advanced Techniques with for i in range()

A visual on advanced techniques using for i in range() in Python.

Beyond basic looping, the for i in range() construct can be integrated with other Python functions to achieve more advanced iteration techniques. Nested loops using range() enable the creation of multi-dimensional structures like grids and matrices. Additionally, integrating functions like enumerate() and zip() can increase the flexibility and power of your loops.

Using enumerate() for Indexed Looping

Using enumerate() in conjunction with for i in range() allows you to loop over a sequence while keeping track of the index. This is particularly beneficial for operations that require both the index and the value of elements.

For example, for index, value in enumerate(my_list): provides both the index and the value of my_list in each iteration. This method enhances readability and efficiency, especially when you need to perform indexed operations such as modifying elements or performing calculations based on their position.

Combining zip() with for i in range()

Using Python’s zip() function with for i in range() allows you to iterate over multiple sequences in parallel. For instance, for a, b in zip(list1, list2): iterates through both list1 and list2 simultaneously, creating pairs of corresponding elements.

This approach simplifies code that requires simultaneous access to multiple iterables and is memory efficient because zip() creates an iterator that generates tuples on demand rather than storing them all at once. This combination is particularly useful for tasks that involve parallel processing of data from multiple sources.

Handling Large Ranges Efficiently

Handling large ranges efficiently requires strategies such as lazy evaluation, where objects are produced only when needed, improving performance. Python’s range function inherently supports lazy evaluation, making it suitable for working with large data sets without consuming excessive memory.

Additionally, tools like the bisect module can be used for efficient searching within sorted ranges, further enhancing performance when dealing with large sequences. These techniques help ensure your code remains efficient and scalable, even when processing extensive ranges of data.

Comparison with Other Iteration Methods

A comparison chart of different iteration methods in Python including for i in range().

Python’s different iteration methods offer various advantages and use cases. The for i in range() loop is ideal for performing operations a specific number of times, while direct iteration over sequences is more straightforward for accessing elements of a list or string without managing a loop counter.

While loops offer more flexibility for non-counter-based conditions, making them suitable for scenarios where the number of iterations is not known upfront. List comprehensions provide a concise and readable alternative for generating lists based on iteration conditions.

Direct Iteration Over Sequences

Direct iteration allows you to access each element in sequences like lists and strings without needing to use indices, making your code more readable. For example,

for item in my_list:

iterates directly over the elements of my_list. Using zip() with direct iteration can simplify code by enabling parallel processing of data from multiple sequences. This approach often enhances clarity and reduces the complexity of loops compared to traditional methods.

for i in range()

Using While Loops

While loops provide a flexible way to iterate until a condition is no longer true, unlike for loops which run for a predetermined number of iterations. For example, while condition: continues looping as long as the condition is true, making it suitable for scenarios where the number of iterations isn’t known beforehand.

While loops are preferable for tasks requiring a variable number of iterations or complex conditional checks. However, for loops with range() are generally faster due to lower overhead in execution.

List Comprehensions

List comprehensions provide a concise way to create lists in Python, using a single line of code to define the list’s content. For instance,

[x**2 for x in range(10)]

generate a list of squares from 0 to 9. They provide a syntactic alternative to traditional for loops, particularly for creating new lists from existing iterables. List comprehensions typically improve performance by reducing overhead in Python’s looping constructs.

This method is especially useful for tasks involving the clean and readable generation and processing of lists.

Introducing Fonzi

Fonzi is a curated AI engineering talent marketplace that connects companies to top-tier, pre-vetted AI engineers. Unlike traditional job boards or black-box AI tools, Fonzi delivers high-signal, structured evaluations with built-in fraud detection and bias auditing, ensuring companies find the best candidates efficiently and reliably.

How Fonzi Works

Fonzi facilitates a streamlined hiring process by connecting skilled AI engineers with leading companies through Match Day events. During these events, companies present salary-backed offers to selected candidates, enabling rapid evaluation and matching.

Benefits of Using Fonzi

Using Fonzi ensures faster hiring, reducing the time to fill AI roles. Most hires through Fonzi happen within three weeks, demonstrating its capability to deliver fast and effective hiring solutions.

Additionally, Fonzi enhances hiring efficiency by significantly reducing the time taken to screen candidates and increasing the quality of hires.

Summary

In summary, the range() function in Python is an indispensable tool for constructing numerical sequences and controlling loops. Whether using one, two, or three parameters, range provides flexibility and precision in iteration tasks. The for i in range() loop leverages these sequences for various applications, from basic looping to advanced techniques with enumerate() and zip(). Practical examples like generating multiplication tables, iterating over lists, and creating nested loops showcase its versatility.

As you incorporate these concepts into your programming, you will find your code becoming more efficient and readable.

FAQ

What is the purpose of the range() function in Python?

What is the purpose of the range() function in Python?

What is the purpose of the range() function in Python?

How does the range() function work with one, two, and three parameters?

How does the range() function work with one, two, and three parameters?

How does the range() function work with one, two, and three parameters?

What are the advantages of using for i in range() over while loops?

What are the advantages of using for i in range() over while loops?

What are the advantages of using for i in range() over while loops?

How can I generate a multiplication table using `for i in range()`?

How can I generate a multiplication table using `for i in range()`?

How can I generate a multiplication table using `for i in range()`?

What is Fonzi, and how does it benefit companies looking to hire AI engineers?

What is Fonzi, and how does it benefit companies looking to hire AI engineers?

What is Fonzi, and how does it benefit companies looking to hire AI engineers?