Skip to main content
HomeTutorialsPython

A Beginner's Guide to Python for Loops: Mastering for i in range

In the realm of Python programming, mastering loops is crucial. This tutorial sheds light on the Python for i in range loop, a fundamental construct in Python.
Jan 2024  · 5 min read

In the realm of Python programming, mastering loops is crucial. This tutorial sheds light on the Python for i in range loop, a fundamental construct in Python that simplifies repetitive tasks. We'll embark on a journey to understand its syntax, versatility, and practical applications.

The Essence of for Loops in Python

A for loop in Python is a control structure used to iterate over a sequence (like a list, tuple, dictionary, or string). The beauty of Python's for loop lies in its ability to iterate directly over items of a sequence in a clear and concise manner.

Syntax of the for Loop

for item in sequence:
    # perform actions

Here, the item represents each element in the sequence, and the loop executes the code block for each element.

Delving into Python's range() Function

The range() function in Python is pivotal for generating a sequence of numbers, offering enhanced control and flexibility in loops.

The Flexibility of range()

Single Argument Usage

  • Generates numbers from 0 to n-1.
  • Example: range(5) produces 0, 1, 2, 3, 4.

Double Argument Usage

  • Specifies the start and end of the sequence.
  • Example: range(10, 15) results in 10, 11, 12, 13, 14.

Triple Argument Usage

  • Adds the ability to specify the step for incrementation.
  • Example: range(1, 20, 2) yields 1, 3, 5, ..., 19.

Practical Applications and Examples

Looping Over Collections

1. Strings: Iterate over each character.

for char in "Hello":
    print(char)
H
e
l
l
o

This loop iterates over each character in the string "Hello". The for loop assigns each character ('H', 'e', 'l', 'l', 'o') in turn to the variable char and prints it. So, the output will be each character of "Hello" on a new line.

2. Lists: Traverse through list items.

for num in [1, 2, 3]:
    print(num)
1
2
3

Here, the loop goes through the list [1, 2, 3]. In each iteration, num takes on the value of the next element in the list, starting with 1, then 2, and finally 3. Each number is printed, resulting in the numbers 1, 2, and 3 each appearing on a new line.

3. Dictionaries: Access keys and values.

for key, value in {'a': 1, 'b': 2}.items():
    print(key, value)
a 1
b 2

This loop iterates over a dictionary containing two key-value pairs ('a': 1 and 'b': 2). The method .items() returns a view object that displays a list of a dictionary's key-value tuple pairs. In each iteration, key and value are assigned the key and value of the next item in the dictionary, which are then printed.

Loop Control Mechanisms

1. The break Statement: Terminates the loop prematurely.

for i in range(10):
    if i == 5:
        break

This code iterates from 0 to 9 (as generated by range(10)). When the value of i reaches 5, the if statement condition is met, triggering the break statement. This stops the loop, even though it hasn't iterated over all the values up to 9.

2. The continue Statement: Skips the current iteration.

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
1
3
5
7
9

This loop also iterates from 0 to 9. However, the if statement checks if i is an even number (this is what i % 2 == 0 does – it checks if the remainder when i is divided by 2 is 0). If it is even, the continue statement is executed, which skips the rest of the loop body for that iteration. Therefore, only odd numbers are printed

Advanced Techniques Using for Loops

1. Nested Loops

This is an example of nested loops, where one loop is inside another. The outer loop (for i in range(3)) iterates through the numbers 0, 1, and 2. For each iteration of the outer loop, the inner loop (for j in range(3)) also iterates through the numbers 0, 1, and 2. The print(i, j) statement is executed for each combination of i and j.

for i in range(3):
    for j in range(3):
        print(i, j)
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

The output will be a series of pairs representing all combinations of i and j in the range 0 to 2.

2. Looping With Enumerate

The enumerate function adds a counter to an iterable and returns it in a form of an enumerate object. This object can be used directly in for loops. In this example, the for loop is used with enumerate on a list ['a', 'b', 'c'].

for index, value in enumerate(['a', 'b', 'c']):
    print(index, value)
0 a
1 b
2 c

The enumerate function adds an index to each item in the list, starting from 0 by default. The loop then iterates over this enumerate object, unpacking each item into index and value. The index is the index of each item, and value is the corresponding item from the list. So, the output will be a series of lines with the index and value.

These examples illustrate how nested loops can be used to perform complex iterations and how enumerate can be used for easy tracking of the index of items in a loop.

How for Loops are used in Data Science

The for loop is a crucial concept in Python programming and data analysis. It has a wide range of applications, such as iterating over lists and arrays, which simplifies data manipulation tasks. I frequently use for loops, particularly nested loops, to efficiently manage multi-dimensional data structures, an essential step in creating machine learning algorithms. Additionally, data scientists often combine for loops with conditional logic for complex data processing, such as aggregating data, like calculating the mean of a list of numbers.

However, for loops may not be the best option when working with large datasets and deep learning algorithms. That's why we have libraries like NumPy, pandas, and PyTorch, which are optimized for vectorized operations, making them more efficient for large-scale data manipulation.

Conclusion: Embracing Loop Efficiency

In conclusion, Python's for loop is an indispensable tool for programmers. Its simplicity, coupled with the power of the range() function, makes it ideal for a variety of iterative tasks in data science and general programming. As you practice and apply these concepts, you'll find your Python code becoming more efficient and expressive.

You can read more about While Loops in our full tutorial and explore this and other concepts in our Intermediate Python course.


Photo of Abid Ali Awan
Author
Abid Ali Awan

I am a certified data scientist who enjoys building machine learning applications and writing blogs on data science. I am currently focusing on content creation, editing, and working with large language models.

Topics

Learn More Python! 

Course

Intermediate Python

4 hr
1.1M
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

Python Loops Tutorial

A comprehensive introductory tutorial to Python loops. Learn and practice while and for loops, nested loops, the break and continue keywords, the range function and more!
Satyabrata Pal's photo

Satyabrata Pal

22 min

tutorial

For Loops in Python Tutorial

Learn how to implement For Loops in Python for iterating a sequence, or the rows and columns of a pandas dataframe.
Aditya Sharma's photo

Aditya Sharma

5 min

tutorial

Python While Loops Tutorial

Learn how while loop works in Python.
DataCamp Team's photo

DataCamp Team

4 min

tutorial

Python Range() Function Tutorial

Learn about the Python Range() function and its capabilities with the help of examples.
Aditya Sharma's photo

Aditya Sharma

7 min

tutorial

Emulating a Do-While Loop in Python: A Comprehensive Guide for Beginners

Explore how to emulate a "do-while" loop in Python with our short tutorial. Plus discover how to use it in data science tasks.
Abid Ali Awan's photo

Abid Ali Awan

5 min

tutorial

For Loops in R

When you know how many times you want to repeat an action, a for loop is a good option. Master for loops with this tutorial.
Ryan Sheehy's photo

Ryan Sheehy

5 min

See MoreSee More