Table of Contents
ToggleThe for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple, or string. It performs the same action on each item of the sequence. This loop starts with the for keyword, followed by a variable that represents the current item in the sequence. The in keyword links the variable to the sequence you want to iterate over. A colon (:) is used at the end of the loop header, and the indented block of code beneath it is executed once for each item in the sequence.
for iterating_var in sequence: statement(s)
Here, the iterating_var is a variable to which the value of each sequence item will be assigned during each iteration. Statements represent the block of code that you want to execute repeatedly.
The following flow diagram illustrates the working of a for loop:
A string is a sequence of Unicode letters, each having a positional index. Since it is a sequence, you can iterate over its characters using the for loop.
The following example compares each character and displays if it is not a vowel ('a', 'e', 'i', 'o', 'u').
zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
'''
for char in zen:
if char not in 'aeiou':
print(char, end='')
On executing, this code will produce the following output:
Btfl s bttr thn gly. Explct s bttr thn mplct. Smpl s bttr thn cmplx. Cmplx s bttr thn cmplctd.
Python’s tuple object is also an indexed sequence, and hence you can traverse its items with a for loop.
In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.
numbers = (34, 54, 67, 21, 78, 97, 45, 44, 80, 19)
total = 0
for num in numbers:
total += num
print("Total =", total)
On running this code, it will produce the following output:
Total = 539
Note: The for loop is a powerful tool for iterating over sequences in Python. It simplifies repetitive tasks and makes your code more readable and efficient.
