Guide to Python For Loops with Solved Examples

Analytics Vidhya Last Updated : 29 Jan, 2024
6 min read

Introduction

Consider that you are planning a concert and that you have a lineup of artists. You must now tell the audience each performer’s name. Each name would need to be announced separately, which would be very time-consuming and tiresome. Here, the Python for loop’s strength is put to use. It helps eliminate the requirement of separately writing the announcement for each performer. 

Here’s how it can be done:

performers = [“Ankit”, “Aryan”, “Bhavesh”, “Chirag”]

for performer in performers:

print(“Ladies and gentlemen, please welcome”, performer, “to the stage!”)

By using the for loop in this way, we can simply announce the names of each performer with only a few lines of code instead of having to create separate print statements for each performer.

We shall examine the Python for loop idea and its importance in programming in this post. For you to comprehend and master the Python for loop, we will delve into the syntax, examine cutting-edge strategies, and offer helpful examples. 

What is Python For Loop?

Python’s for loop is a key control structure that enables you to cycle through a list of items. By automating the repeated execution of a code block, you may effectively complete repetitive activities. To iterate across lists, tuples, strings, dictionaries, and other iterable objects, Python programmers frequently use the for loop.

For loop
Source: Linux and Ubuntu

Also Read: Everything You Should Know About Built-In Data Structures in Python 

Basic Syntax of For Loop in Python

The syntax of a for loop in Python is straightforward. 

Here’s the basic structure:

for variable in iterable:

    # Code block to be executed

The variable represents the current element in the iteration, and the iterable is the sequence or collection over which the loop iterates. The code block indented under the for statement is executed for each element in the sequence.

Here is an example to help you understand the basic syntax of a for loop:

fruits = ["apple," "banana," "orange"]

for the fruit in fruits:

    print(fruit)

Now the for loop will iterate over the list of fruits, printing the name for each fruit.

Output:

apple

banana

Orange

Range Function and For Loop in Python

The range() function is commonly used for loops in Python. It creates a sequence of numbers that help determine the number of times the loop iterates. The three arguments for the range() function are as follows:

  • Start
  • Stop
  • Step

Here is an example of how to use a for loop and the range() function:

Example 1: range(6)

This variant generates a sequence of numbers starting from 0 (inclusive) up to, but not including, the specified stop value, which in this case is 6. It will generate the numbers 0, 1, 2, 3, 4, and 5. The general syntax is range(start, stop, step), but if you omit the start value, it defaults to 0, and if you omit the step value, it defaults to 1.

for i in range(6):

    print(i)

Output:

0

1

2

3

4

5

Example 2: range(3, 6)

This variant generates a sequence of numbers starting from the specified start value, which in this case is 3 (inclusive), up to, but not including, the specified stop value, which is 6. It will generate the numbers 3, 4, and 5.

for i in range(3, 6):

    print(i)

Output:

3

4

5

Example 3: for i in range(1, 6, 2)

for i in range(1, 6, 2)

    print(i)

Thus, the for loop will iterate over the numbers from 1 to 6 with a step of 2. 

Output:

1

3

5

Nested For Loop in Python

Python allows you to nest one or more loops within another loop. This is known as a nested for loop. These are helpful in conditions when you need to iterate over multiple sequences or carry out iterations within iterations.

Here’s an example of a nested for loop that prints the multiplication table from 1 to 5:

for i in range(1, 6):

    for j in range(1, 11):

        print(i * j, end="\t")

    print()

In this illustration, the inner for loop iterates from 1 to 10 while the outside for loop iterates over the integers 1 to 5. The multiplication table is produced and shown using the print() function.

Checkout: Everything a Beginner should know about Classes and Objects in Python Before Starting Your Data Science Journey

Control Statements in For Loop in Python

Python provides control statements such as break and continue that can be used within a for loop to control the flow of execution.

The break statement allows you to exit the loop prematurely based on a certain condition. It ends the loop and gives the next sentence, which follows the loop, control.

The continue statement advances to the following iteration without running the remaining code in the block for the current iteration. It gives you the option, under certain circumstances, to skip particular items in a sequence.

These control statements provide flexibility and enable you to fine-tune the behavior of your for loop based on specific requirements.

Break Example

for i in range(10):
  print(i)
  if i==5:
    break
print("loop ended")

Output:
0
1
2
3
4
5
loop ended

Continue Example


for i in range(10):
  print(i)
  if i==5:
    print("if condition checked, let's 'continue' ")
    continue
    print("This statement will not be printed because control has moved to the starting of loop.")

Output:
0
1
2
3
4
5
if condition checked, let’s ‘continue’
6
7
8
9

List Comprehension and For Loop in Python

List comprehension is a concise and powerful technique in Python that allows you to create new lists based on existing lists using a single line of code. It combines the for loop and an optional filtering condition within square brackets.

Here is an example that demonstrates list comprehension:

numbers = [1, 2, 3, 4, 5]

squared_numbers = [x ** 2 for x in numbers]

print(squared_numbers)

The for loop will iterate over each element in the numbers list, square it, and add it to the squared_numbers list.

Output:

[1, 4, 9, 16, 25]

List comprehension provides a concise and elegant way to manipulate lists, making your code more readable and expressive.

Iterating Through String and Tuple Using For Loop in Python

The for loop may cycle over other iterable objects besides lists, such strings and tuples. Each character in a string or each component of a tuple is treated as a separate item in the loop.

Here is an illustration of how to use a for loop to iterate over a string:

message = "Hello, Python!"

For char in message:

    print(char)

In this case, the for loop iterates and prints over each character in the message string. 

The output will be:

H

e

l

l

o

,

P

y

t

h

o

n

!

Similarly, using a for loop, you can iterate through tuples and perform operations based on individual elements.

Iterating Through Dictionaries Using For Loop in Python

Despite the fact that dictionaries lack the intrinsic iterability of lists or tuples, you may iterate using them in a loop. The loop iterates through the dictionary’s keys by default.

Example:

student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78}

for student in student_grades:

    print(student, ":", student_grades[student])

In this example, the for loop iterates over each key in the student_grades dictionary and prints both the student’s name and their corresponding grade. The output will be:

Alice: 85

Bob: 92

Charlie: 78

To iterate over the values or both keys, you can use the values() method. On the other hand, to iterate over values of a dictionary, use the items() methods.

Conclusion

Mastering the for loop enables you to efficiently process data, automate repetitive tasks, and write more concise code. Remember to practice and experiment with different examples to solidify your understanding. So, start harnessing the potential of the for loop in Python and take your programming skills to the next level. Enroll in our free python course and learn all the major techniques!

Frequently Asked Questions

Q1. Can I have nested for loops in Python?

A. Yes, Python allows you to nest one or more loops within another loop. This is called a nested for loop. It is useful when you must iterate over multiple sequences or perform iterations within iterations.

Q2. What does Python’s list comprehension mean?

A. With only one line of code, you may build new lists based on existing ones using Python’s succinct and potent list comprehension approach. Within square brackets, it combines the for loop with a potential filtering condition.

Q3. Can I use a for loop to iterate through a string or a tuple?

A. Yes, a for loop can iterate through strings and tuples. Each character in a string or each element in a tuple is treated as an individual item in the loop, allowing you to perform operations based on those elements.

Analytics Vidhya Content team

Responses From Readers

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details