Python For Loops Explained With Examples

Python is a general-purpose, high-level programming language designed to be easy to read and execute. It is open-source, which means it is free to use. In this article, we will learn one of Python programming's fundamental looping statements: the Python for loop.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Is for Loop in Python?

The for loop in Python is used to iterate over a sequence, which could be a list, tuple, array, or string.

Syntax: FOR COUNTER IN SEQUENCE:

  STATEMENT(S)

Block Diagram:

Fig: Flowchart of for loop

Example:

basic

Fig: Basic example of Python for loop

The program operates as follows: We have assigned a variable, x, which is going to be a placeholder for every item in our iterable object. In this case, the variable “x” actually represents the elements in that list. Then, we print our variable, x. This process continues until all items are printed.

Break Statement in for Loop

The Python break statement is used to exit from the loop immediately after a certain condition is met.

Example:

break-statement

Fig: break statement

The program above operates as follows: The loop continues until the specified element is encountered. As soon as the ‘green’ element is encountered, the loop breaks. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Continue Statement in for Loop

The function of the continue statement is to skip the current iteration of a loop and continue with the next one.

Example:

continue

Fig: continue statement

The Range() Function

The range() function executes a group of statements for a specified number of times.

Example:

range

Fig: range() function in Python for loop

The program operates as follows. When the for structure begins executing, the function

range creates a sequence of values, which range from zero to four. The first value in this sequence is assigned to the variable x, and the body of the for structure executes. For each subsequent value in the sequence, the value is assigned to variable x, and the body of the for structure executes. This process continues until all values in the sequence have been processed.

Else in for Loop

Python enables an else clause at the end of a for loop. The else part is executed if the loop terminates naturally.

Example:

else

Fig: else statement

In the above example, the for loop is executed first. After that, the else part is executed.

Nested Loops

A loop inside another loop is called a nested loop. The inner loop will be performed once for each iteration of the outer loop.

Example:

nested

Fig: Nested loop in Python for loop

Recommended programming practice:

Excessive nesting levels can make it difficult to follow the program. As a general rule, try to avoid using more than three levels of indentation.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Access Index in for Loop

To iterate over the indices in a sequence, we use the enumerate() function.

Example:

enumerate

Fig: enumerate() function

The enumerate() function adds the counter to iterable, which starts from zero by default.

Looping Through Multiple Lists

We can loop through multiple lists at once. For this, we use the zip() function, which is built in the Python loop.

Example:

looping.

Fig: Looping through multiple lists

For loop Exercise

Question 1: Display a “simplilearn” message after successfully executing for loop

Solution:

q1

Fig: Question 1 solution

Question 2: You are given a list of integer elements. Make a new list that will store squares of elements from the previous list.

Solution:

q2

Fig: Question 2 solution

Iterating by Using Index of Sequence Code Output

In python, one can iterate with the help of an index of sequential code in For Loop such as string with a For Loop, list with a For Loop, and tuple with a For Loop.  

How to Iterate Over a String With a For Loop

A string with a For Loop can be iterated with the help of single, double or triple quotes for characters or numbers. Eg 'Hello World!' in single quotes, "hello" in double quotes or '''hello''' in triple quotes. 

Example: 

In [1] #indexing
H="Hello" 
print(H[0])
#negative indexing
print(H[-4]) 

Image Reference

String Output: 

H

How to Iterate Over a List With a For Loop

Square bracket is used for a python list with a For Loop. Besides, There are various types of inbuilt functions in the list  that we can apply for particular tasks. 

Such as 

  • clear() function to remove the elements from the list
  • copy() function to return a copy of elements from the list
  • insert() function to add a specific element to a specific position
  • append() function to add elements in the end of the list
  • pop() function to remove element from a particular position
  • remove() function to remove the elements with particular value from the list
  • reverse() function to make the order of the list reverse 
  • count() function to return the number of elements with specified value
  • index() function to return an index of the elements in the list

Example: 

num=[4, 5, 6, 7] 
print(num)

letter=['p', 'q', 'r', 's'] 
print(letter)

Image Reference

List Output: 

[4, 5, 6, 7]

['p', 'q', 'r', 's']

How to Iterate Over a Tuple With a For Loop

Tuple is used to hold data types by enclosing parentheses "()" and commas to separate every different element. Also, for index as an integer value, we write parenthesis in square bracket form ([1]). 

Example 

City= ("Nagpur", "Pune", "Nashik", "Mumbai", "Delhi", "Goa") 

print (city[2])

Image Reference

Tuple Output: 

Nashik 

How to Iterate Over a Set With For Loop

Usually items in a Set are kept in random form, they don't have a specific index. However, with the help of 'in' keyword and for loop in python, we can loop the items in set with specified value. 

Example: 

thisset = {"wheat", "bajra", "pulses", "rice"}

for x in thisset:

print(x)

Image Reference

Set Output: 

wheat 

bajra

pulses 

rice

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

How to Iterate Over a Dictionary With For Loop

A Dictionary with a For Loop in Python can be used to return a value with specified rules. 

Example: 

In the below example, the dictionary function can return a value as well as a key concerning a particular item. 

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
} 
for x, y in thisdict.items():
print(x, y)

Image Reference

Dictionary Output: 

brand Ford

model Mustang

year 1964

for loop With else Output

Else in for loop can be executed if the for loop terminates naturally first and later else output can be executed.

Example: 

In [1] : colours = ['purple', 'blue', 'white', 'golden']
For x in colours:
print(x) 
else: 
printf("finished!")

Image Reference

Else Output: 

purple

blue

white

golden

finished! 

While Loop

While loop in python is used to execute statements when the condition satisfies the true value. While loop requires to define a specific relevant variable such as indexing variable 'i' = 1. 

Example: 

i= 1, 
while i<7 :
print(i)
i+=1

Image Reference

While Output: 

1

2

3

4

5

6

Single Statement While Block Note

This is similar to if statement when a while Statement has only a single statement. Thus it can be put with a header line. 

Example: 

flag = 1
while (flag): print 'This is my home!'
print "Good bye!

Image Reference

Output: 

This is my home!  

for in Loop Syntax Output

Syntax: 

For counter in sequence: 

Statement (S) 

Loop Control Statements

There are 3 different types of Loop control Statements in python, they are continue, break and pass concerning requirements of the loop. 

Continue Statement

Continue Statement in Python is used to iterate the next element in the loop by skipping the current iteration. 

Example: 

In [1] : colours = ['purple', 'blue', 'white', 'golden']
For x in colours:
print(x) 
if x=="white": 
continue

Image Reference

Continue Output: 

purple

blue

white

golden 

Break Statement

Break Statement in Python is used to exit from a loop under certain conditions. In the below example, the statement breaks at 'white' and only executes the elements before 'white' .

Example: 

In [1] : colours = ['purple', 'blue', 'white', 'golden']
For x in colours:
print(x) 
if x=="white": 
break 
Break Output: 
purple
blue
white

Image Reference

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Pass Statement

Pass Statement in Python is used when the user doesn't know which particular code should be written. This is also called a null statement. We usually write comments in the code, though it is ignored by the interpreter and there is no effect on code. However, with pass Statement can be used in conditional statement format to define the various elements. 

Example: 

a=20

b=40

if (a<b):

pass

else: 

printf("b<a") 

How Does the "for" loop in Python Work Internally?

Internal for loop in python or one loop into another loop in python also called as nested loop. The iteration of the inner loop in python can be executed every once with respect to every outer loop iteration. 

Example: 

In [1] : colours = ['purple', 'blue', 'white']
fruits= ['mango', "banana", '''apple''']
for x in colours:
for y in fruits:
print(x,y)
Inner For loop (nested loop)

Image Reference

Output: 

purple mango

purple banana

purple apple

blue mango

blue banana

blue apple

white mango

white banana

white apple 

Conclusion

In this article, we have discussed Python for loop and its syntax different statements. We also provided a visual example that demonstrated how to use the break and continue statements in a Python for loop. 

If you have any questions or comments, please post them below, and we'll have our experts get back to you as soon as possible.

About the Author

Aryan GuptaAryan Gupta

Aryan is a tech enthusiast who likes to stay updated about trending technologies of today. He is passionate about all things technology, a keen researcher, and writes to inspire. Aside from technology, he is an active football player and a keen enthusiast of the game.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.