All Posts

Python for Loop

Python for Loop

Python for loop is used to iterate over a set of statements. It is also used to iterate over a sequence. A sequence could be a list, a tuple, a dictionary, a set, or a string in the order that they appear in the sequence. Iterating over a sequence is also called traversing.

Syntax

The syntax of the for loop is given as follows:

for val in sequence:

  statement(s)

 

Indentation separates the for loop’s body from the rest of the code. This enhances the readability of the loop code. When a sequence contains an expression list, it is evaluated first. The first item in the sequence is then assigned to the loop counter variable, ‘val’. After that, the statements block is executed. As the loop continues, each item in the list is assigned to ‘val’, and the statement(s) block is executed until the entire sequence is processed.

Example

Python program to display the contents of a list by using the for loop. The program displays the elements of a list each in a separate line.

#########################################
# Python program using for loop
# Python Tutorials - www.TestingDocs.com
#########################################
marks = [64, 98, 78, 86, 81, 55]
for i in marks:     # for loop
    print(i)

 

 

Python for Loop

Output

64
98
78
86
81
55

Iterate through a list

Let’s look at another example. In this example, the for loop is used to iterate
over the list.

###########################################
# Python program to Iterate through a list
# Python Tutorials - www.TestingDocs.com
###########################################
fruits = ["apple", "banana", "grapes","mango","orange"]
for fruit in fruits:
    print(fruit)

The for loop goes through the list fruits, and in each iteration, the variable fruit takes the value of the next item in the list. The loop then executes the body of the loop, which prints the name of each fruit.

 

Python for loop Iterate List

Output

banana
grapes
mango
orange

—

Python Tutorials

Python Tutorial on this website can be found at:

https://www.testingdocs.com/python-tutorials/

More information on Python is available at the official website: