Home » Python » For Loop in Python

About Reshma Sathe

I am a recent Master of Computer Science degree graduate from the University Of Illinois at Urbana-Champaign.I have previously worked as a Software Engineer with projects ranging from production support to programming and software engineering.I am currently working on self-driven projects in Java, Python and Angular and also exploring other frontend and backend technologies.

For Loop in Python

1. Introduction

Every high-level programming language provides support for loops. Loops repeat a set of instructions until a specific condition is satisfied. One of the most used loops in any language is the “for” loop. In this article, we look at all for loops in the Python programming language.

2. What is a For Loop

A For loop iterates over a sequence of items. Data structures like Lists, tuples, dictionaries, sets, and strings. The basic build of a for loop is as follows:

for [iterator_name] in [list/tuple/dictionary/string/Set]:
      [instructions to do..]

For example, we have a sequence of numbers,

numList = [1,2,3,4,5,6,7,8,9]

We can loop through this list using the for loop as follows:

for n in numList:
     print(n);
python for loop - Simple for loop
Simple for loop

3. Looping through a String

A String in Python is considered a sequence. So, we can use a for loop on a String just like on any other sequence.

3.1 A Simple loop with a string

Python considers a string as a sequence of characters. So, if we run a for loop over a string and print it, Python returns each character separately. These include whitespaces. A simple example

string_name = "We forge the chains we wear in life."
for char in string_name:
    print(char)
print("\n")
python for loop - Simple For loop for a string
Simple For loop for a string

We can output the characters in one line as follows:

for char in string_name:
    print(char, end= ' ')
python for loop - For loop output in a single line
For loop output in a single line

3.2 For loop with enumerate

The for loop in Python iterates over a sequence. It does not keep a count of the iterator or the index. Python has an in-built function called enumerate to ease this task. Enumerate takes two parameters: the sequence and an option start.

Consider an example where we want to print out only the characters having even index. For this example, we would need the enumerate function.

inputString = "To be or not to be, that is the question"
for index,str in enumerate(inputString):
    if index%2 ==0:
        print(str, end =' , ')
python for loop - For loop with enumerate function
For loop with enumerate function

3.3 For loop in reverse order

We can also loop through a String in Python in reverse order. There are two ways of doing so. The first method is to slice the string in the reverse order and then loop through it. The second method is to use the reversed function.

inputString1 = “There is nothing in the world so irresistibly contagious as laughter and good humor.”

#Method 1
print("For Loop with reverse string with slicing")
print("\n")
for c in inputString1[ : :-1]:
    print(c, end =' , ')
print("\n")
  
#Method 2
#length of string
str_length = len(inputString1)
  
#using reversed function
print("For Loop with reverse string with reversed")
print("\n")
for ch in reversed(range(0, str_length)):
    print(inputString1[ch],end=' , ')
print("\n") 
python For loop for a string in reverse order
For loop for a string in reverse order

3.4 For loop with a specific set of elements in a String

We can run a for loop over a specific slice of a string or a sequence. We can do so as follows:

input_string2 = "Laughter is the sun that drives winter from the human face."
print("For loop with string")
print("\n")
for chr in input_string2[0:41:2]: 
    print(chr, end =' , ')
print("\n") 
python For loop over a specific slice.
For loop over a specific slice.

4. For loop over ranges

A range is a data structure that creates a sequence of consecutive elements. It takes two parameters, a start index and an end index, and builds a sequence by including the start index and excluding the end index. We can loop through such a range. We see an example where we use a range of 1 to 20 and print whether the number is even or odd.

for i in range(1,21):
    if i%2 !=0:
        print(i," is even.")
    else:
        print(i, " is odd")
python For loop with range
For loop with range

5. For loop with a break statement

We can use a break statement with the for loop to come out of the loop when a specific condition is satisfied. The break statement makes Python quit the loop entirely. For example:

input_string3 = “He who opens a school door, closes a prison.”
for str in input_string3:
    if str == ",":
        break
    else:
        print(str)

The loop breaks when it encounters a comma, and Python ignores the rest of the input string.

For loop with break clause
For loop with break clause

6. For loop with an else

We can use the else conditional clause with a “for” loop. Python executes the else clause after the entire “for” loop. If the for loop has a break clause, Python executes the else clause only if the break clause is not executed.

As per Python documentation,

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Python 3.7 documentation

The first example shows the else clause executing

num_list= [1,18,90,36,45,80,17,65,49,22,38,15,10,12]
max_num = 99

for num in num_list:
    if num > max_num:
        break
else:
    print("Max number is still", max_num)
print("\n")
Else clause for for loop
Else clause for for loop

In the second example, we use the same code. We have just adjusted the input such that the break runs.

num_list= [1,18,90,36,45,80,100,17,65,49,22,38,15,10,12]
max_num = 99

for num in num_list:
    if num > max_num:
        print("New Max number is: ", num)
        break
else:
    print("Max number is still", max_num)
print("\n")
Else clause not working since break works
Else clause not working since break works

7. Nested Loops

We can nest one for loop inside another. We are allowed to nest as many for loops as we wish, but it is usually not recommended to nest more than two loops inside each other. A classic example of nest loops is prime numbers.

for number in range(2, 20):
     for num in range(2, number):
         if number % num == 0:
             break
     else:
         #The else is for the for loop
         print(number, 'is a prime number')
Nested Loops
Nested Loops

8. Empty For loop

When we want to keep the for loop empty, we can put the “pass” clause inside. If we leave an empty for loop without any code inside, Python throws an “expected an indented block” error.

for i in range(1,10):
Empty loop error
Empty loop error

To avoid the above error, the code should be

for i in range(1,10):
   pass 

9. Summary

In this article, we looked at examples of “for” loops in Python. A for loop is one of the most useful and widely used loops in Python and has many valuable options that we can use to perform a wide variety of tasks.   

11. Download the Source Code

That was a tutorial about the For loop in Python.

Download
You can download the full source code of this example here: For Loop in Python

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments