Python for Loops - A Step-by-Step Guide

Tutorial Playlist

In Python, ‘for loops’ are the fundamental control flow statements that are generally used to execute the particular condition in the block of code repeatedly for a fixed number of iterations. In contrast to other traditional programming languages where ‘for loops’ typically require condition checks and increment operations manually, Python simplifies this whole process by depending on the sequence iteration.

Now in this tutorial, you are going to learn everything about Python for loops including its syntax, working examples, and best practices. We will also help you to explore the more advanced concepts like nested for loops, loop interruptions, filtering data using for loops, and many more. Let’s learn and master ‘for loops’ to enhance your Python programming skills.

What are For Loops in Python?

For Loops in Python are primarily used to iterate through sequences such as lists, strings, tuples, dictionaries, sets, and even custom collections. Every iteration simply processes one element at a time which makes it efficient for various tasks like data traversal, complex calculations, and creating patterns.

The for loops in Python continue till all the elements in the sequence are processed. Unlike while loops, for loops handle the sequence automatically and do not require manual condition checks which makes it a suitable and preferred choice for many programming requirements.

When to Use For Loops

  • Sequential Iterations: When you need to iterate over a sequence (like lists, strings, or ranges) in a linear manner.
  • Fixed Number of Iterations: When the number of repetitions is pre-known or can be defined based on the size of a sequence.
  • Data Processing: When you have to filter, transform, or process data in a data structure such as lists, dictionaries, or files.
  • Pattern Generation: For generating formatted patterns in console outputs, i.e., number or star pyramids.
  • Nested Iterations: In the case of multi-dimensional data structures like lists of lists or matrices.

How to Use For Loops in Python

For loops in Python are used for sequential iterations for a certain number of times, that is, the length of the sequence. Iterations on the sequences in Python are called traversals.

Syntax of for loops in Python

Let us see the Python Syntax of For Loop with examples:

for a in sequence:
body of for loop

Working of For Loops in Python

The following flowchart explains the working of for loops in Python:

Working of For Loops in Python

  1. Start of Loop: First, the for loop starts with selecting the first item(with zeroth index) from the sequence like lists, strings, range, etc.
  2. Condition Check:
  • The for loop then simply checks whether the last element has been reached.
  • If it had been reached, meaning yes, then, the loop will terminate, and the control flow moves to the statement after the loop.
  • If not, then the body of the loop will get executed.
  1. Body Execution:
  • The condition present inside the code block inside the for loop executes for the current item in the sequence.
  • This may typically involve operations like calculations, printing, or modifying data.
  1. Move to the Next Element: The for loop then moves to the next item in the sequence automatically.
  2. Repeat Until the End: Steps 2 to 4 will be repeated until all elements in the sequence have been processed.
  3. Exit Loop: Once the sequence reaches its end, the control then exits the loop and continues with the code after it.

Code Example for better understanding:

Python

Output:

Code Example Output

Now In this example, the loop iterates through each fruit, processes it by printing, and exits after all elements are traversed, as shown in the flowchart.

Python Programming: From Basics to Mastery
Learn Python Syntax, Libraries, and Frameworks for Data Science and Development
quiz-icon

How to Use For Loops on Strings in Python

In Python, strings are sequences of characters, and for loops can be used to iterate over each character in a string. This is helpful when you need to manipulate or analyze each character individually.

Example:

Python

Output:

Loops on Strings in Python Output

Common Use Cases:

  • Counting the number of specific characters in a string.
  • Checking if certain characters exist in a string.
  • Modifying or reversing strings.

How to Use range() Function In Python For Loops

We can specify a particular range using an inbuilt Python function, named range(), to iterate the loop a specified number of times through that range.

Example:

Python

Output:

Function In Python For Loops Output

Note: The range here is not from 1 to 10 but from 0 to 9 (10 numbers).

  1. Specifying start and stop points in the range() function:

Example:

Python

Output:

stop points in the range() function Output

Note: Here, in this example, the starting point is 3 and the ending point is 7. So, the list will be generated from 3 to 6 (4 numbers).

  1. Using Python for loops with the range() function:

Example:

We can simply use Python For loop with the range() function as shown in the example below.

Python

Output:

loops with the range() function Output

By default, the increment in the range() function when used with loops is set to 1; however, we can change or specify a particular increment by including a third parameter in the range() function, as illustrated in the following example:

Python

Output:

increment in the range Output

Get 100% Hike!

Master Most in Demand Skills Now!

Loop Interruptions in Python For Loops

1. Break Statement

Just as in while loops, for loops can also be prematurely terminated using the break statement. The break statement will immediately terminate the execution of the loop and transfer the control of the program to the end of the loop.

Example:

Python

Output:

Break Statement Output

2. Continue Statement

Just as with while loops, the continue statement can also be used in Python for loops to terminate the ongoing iteration and transfer the control to the beginning of the loop to continue the next iteration.

Python

Output:

Continue Statement Output

Note that the fifth iteration was interrupted as we have used the continue statement when the value of i is 5. Therefore, the control was passed to the beginning of the loop, and the program started executing the sixth iteration and did not print the value of i when it was 5.

Python for Data Science and Automation
Automate Tasks and Analyze Data with Python’s Powerful Libraries
quiz-icon

Else in Python For Loops

For loop in Python can have an optional else block. The else block will be executed only when all iterations are completed. When break is used in for loop to terminate the loop before all the iterations are completed, the else block is ignored.

Example:

Python

Output:

Else in Python For Loops Output

Nested For Loop in Python

As the name suggests, nested loops are the loops that are nested inside an existing loop, that is, nested loops are the body of another loop.

Example:

Python

Output:

Nested For Loop in Python Output

In the above example, we have used nested loops to print a number pyramid pattern. The outer loop is used to handle the number of rows in the pattern, and the inner loop or the nested loop is used to handle the number of columns in the pattern. Note that we have also used the third parameter in the range() function and have set the increment to 2, that is why the number in every column is incremented by 2.

For Loops in Python Data Structures

In Python, there are many data structures such as lists, tuples, sets, and dictionaries that generally provide the versatility to store and organize different kinds of data. For Loops in Python are very important concept in order to perform iterations over these data structures that typically make it very easy to process, filter, and modify their content efficiently. Here we have explained how you can use them for loops in Python Data Structures.

1. Lists

Lists are ordered, mutable collections where you can hold elements of any data type. For loops can be applied for traversals and manipulating each list element.

Example:

Python

Output:

Lists Output

Use Cases:

  • Applying functions to each list element
  • Filtering elements based on conditions
  • Creating new lists using list comprehensions

Nested Loops on Lists:

Python

Output:

Nested Loops on Lists Output

2. Tuples

Tuples are fixed, ordered groups and can be used for fixed data. For loops can also be applied in the same manner you’d apply them for lists.

Example:

Python

Output:

Tuples Image

Use Cases:

  • Iterating over multiple fixed values
  • Handling return values from functions

Advantages Over Lists:

Tuples are also faster and require less space, and thus appropriate when data is not supposed to be modified.

3. Sets

Sets are groups of distinctive elements where the order is not specified. For loops can nevertheless allow access through each element even when the order is not specified.

Example:

Python

Output:

Sets Output

Use Cases:

  • Removing duplicates from data handling
  • Performing mathematical set operations like union and intersection

Important Note: Since sets are not arranged, successive iterations can provide different orders.

4. Dictionaries

Dictionaries store key-value pairs and are one of the most commonly used data structures in Python. For loops can be used to iterate over keys, values, or both.

  1. Iterating Over Keys
Python

Output:

Iterating Over Keys Output

  1. Iterating Over Values
Python

Output:

Iterating Over Values Output

  1. Iterating Over Key-Value Pairs
Python

Output:

Iterating Over Key-Value Pairs Output

Use Cases:

  • Extracting information from structured data
  • Updating or restructuring the key-value pairs
  • Data aggregation activities

Handling Nested Dictionaries:

Python

Output:

Handling Nested Dictionaries Output

Enumerate Function in Python For Loops

The enumerate() function adds the counter for the iterable and returns the value and the index for each pass through the loop. This is useful when you need the capability for the ability to know the loop position.

Syntax:

Python

Output:

  • iterable: Any iterable (like lists, strings, or tuples)
  • start: The starting index (default is 0)

Example:

Python

Output:

Enumerate Function in Python For Loops

Benefits of Enumerate:

  • Avoid manually counting counter variables
  • Cleaner and easier to read

Reverse for loops in Python

We can invert the for loop in Python in two ways:

  1. One is by utilizing the reversed() function.
Python

Output:

Reverse for loops in Python

  1. The second method is using range(n,-1,-1)
Python

Output:

Reverse for loops in Python

How to Use For Loops to Flatten Nested Lists (2D Lists)

Nested lists, also known as two-dimensional lists, are lists of lists. They can be used for the description of grids, tables, or matrices. Flattening the nested list is the conversion of the nested list into a one-dimensional list form. This can be achieved through nested for loops where the outer for loop iterates over each sublist and the inner for loop iterates over each element in each sublist.

Example:

Python

Output:

Loops to Flatten Nested Lists

How to Use the Zip Function with For Loops

The zip() function is applied for parallel iterations over multiple sequences (lists, tuples, etc.). This pairs elements from each list together (or n-tuples when multiple lists are provided). This is helpful for combining associated data from two lists.

Example:

Python

Output:

Zip Function with For Loops

Looping Backward with a Negative Step in Range

In Python, range() also accepts the start, stop, and step parameters. For looping backward, the step is given a negative value. This is useful for those operations where you require counting backward or need the reversal of the sequences.

Example:

Python

Output:

Looping Backward with a Negative Step in Range

How to Filter Data Using For Loops

Data filtering is the act of selecting elements for some given criteria. One simple technique for data filtering using only the base libraries is the for loop. This is beneficial for data cleansing and data verification processes.

Example:

Python

Output:

How to Filter Data Using For Loops

How to Create Patterns Using For Loops

Pattern generation is one good technique for practicing and understanding nested loops. In this case, the outer loop is for the rows, and the inner loop is for the columns, printing the ‘*’ for the triangle pattern.

Example:

Python

Output:

How to Create Patterns Using For Loops

Example Questions on Python For Loops

1. Counting Even and Odd Numbers in a List

A for loop can be used to traverse a list and check if each element is even or odd. The modulo operator (%) helps determine whether a number is divisible by 2. If the remainder is zero, the number is even; otherwise, it’s odd.

Example:

Python

Output:

Counting Even and Odd Numbers in a List

2. Finding the Maximum Number in a List

To find the highest value from the list by using the list elements alone, the variable value is assigned the value of the list’s first element. In the list loop, each value is matched against the highest value, and the variable is assigned when the value is larger.

Example:

Python

Output:

Finding the Maximum Number in a List

3. Reversing Each Word in a String List

This task involves looping through the list of strings and reversing each word. To reverse the letters of a word, the slice operation is performed using the syntax [::-1].

Example:

Python

Output:

Reversing Each Word in a String List

4. Sum of Digits in a Number

This problem involves splitting the given figure into individual digits, converting them into integers, and summing them up. For looping through the given figure in the form of the string, the for loop is being used.

Example:

Python

Output:

Sum of Digits in a Number

5. Printing a Multiplication Table

To display the multiplication table for the specified number, a for loop iterates through the range and multiplies the specified number by each value from the range.

Example:

Python

Output:

Printing a Multiplication Table

6. Checking for Prime Numbers

A prime number is a number greater than 1 that has no divisors other than 1 and itself. To check if a number is prime, a for loop iterates from 2 to the square root of the number, checking if it’s divisible by any number.

Example:

Python

Output:

Checking for Prime Numbers

Difference between For and while loop in Python

Parameter For Loop While Loop
Format It allows initialization, condition checking, and iteration statements that are written on the top of the loop. It only allows initialization and condition checking at the top of the loop.
Declaration for(initialization; condition; iteration){ //body of ‘for’ loop} while ( condition) { statements; //body of loop}
Condition It iterates infinite time if no condition is given. It shows an error if no condition is given.
Initialization If initialization is once done in the “for” loop, it never is repeated. If initialization is done while condition checking, then it is required each time when the loop iterates itself.
Iteration Statement As the iteration statement is written at the top, it will execute only after all the statements are executed. The iteration statement can be placed anywhere in the syntax of the loop.

Conclusion

With this, we have come to the end of this Python For Loops Tutorial. Mastering for loops is the essence of writing clean and efficient code. Having knowledge about the syntax, everyday applications, and recent features like the range() function, nested loops, and loop control statements will make you easily handle various coding scenarios.

Start implementing for loops for your projects immediately and unlock their potential. If you need to explore deeper into the domain of Python programming, check out our exhaustive tutorials and interview questions for Python for enhanced coding skills and job opportunities.

FAQs on Python For Loops
1. What is the purpose of a for loop in Python?

A for loop is used for looping through the sequences like lists, strings, and ranges. This is helpful for doing something for every item on the list.

2. How is a for loop different from a while loop in Python?

A for loop iterates over a fixed collection, whereas a while loop iterates through the iterations until some specified condition is fulfilled. For loops are applied when iterations are known.

3. Can we use else with for loops in Python?

Yes, Python also supports the use of the else block for ‘for loops’. If the for loop goes through all the iterations without encountering the break statement, the code under the else block is executed.

4. How do you reverse a for loop in Python?

You can invert the for loop in Python using the reversed() function or by providing the range() function with a decrement value.

5. What is the role of the range() function in Python for loops?

The range() function generates a range of numbers and is generally used for restricting the iterations for ‘for loops’. It can set the start, the stopping value, and the step value.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 15th Mar 2025
₹20,007

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.