Python For loop
The Python for loop has capabilities to iterate the sequences or range. Sequences in Python can be strings, lists, tuples, sets, or dictionaries. It can also generate a list of numbers from the range using the range() function.
The Python for loop is a bit different from what we have in some other programming languages, where it is used just for generating ranges.

for
with string
Using for loop to iterate over the string.
name = 'Logical Python'
for i in name:
print(i)
for
with list
Using for loop to iterate over the list.
numlist = [1,2,3,4,5,6,7,8,9,10]
for i in numlist:
print(i)
for
with range()
function
For loop can also be used to generate the range of numbers using the range() function.
The range() function generates the range of numbers. It can take three arguments:
Start | Number to start from. It is not mandatory argument, default is 0. |
---|---|
Stop | Number to end at, this number is not included. It is mandatory argument. |
Step | If we want to Jump numbers. It is also not mandatory argument, default is 1. |
Example: range(1,10,2). It will start from number 1, end at 10 with step size of 2.
Printing numbers from 0 to 4.
for i in range(5):
print(i)
Printing numbers from 1 to 10 with a step size of 2.
for i in range(1,10,2):
print(i)
for else
We do have an option to add the else block with the for loop. The else
block will execute only if the for loop finishes traversing all the elements. If the for loop breaks in between because of an error, exception, break statement, etc., then the else block will not execute.
Traversing all the elements of the list and executing else block.
name = ['Wills','John','NULL','Arnold']
for i in name:
print(i)
else:
print("All names are good.")
If name is “NULL”, it breaks the loop, and else block is not executed.
name = ['Wills','John','NULL','Arnold']
for i in name:
print(i)
if i == "NULL":
print('"NULL" is not allowed in name. Please correct and try again.')
break
else:
print("All names are good.")
Nested for
The process of using a loop inside the loop is known as the nested loop.
A for loop can also be nested inside another for loop. The inner for loop will be executed for each iteration of the outer for loop.
name = ['American','Indian']
animal = ['Cow','Horse']
for i in name:
for j in animal:
print(i,j)
Without Accessing Elements
For loop can be used without accessing elements of the sequence. For example, if we have to print “Hello” 5 times. In this case, we need not access elements of the for loop.
Generally, we use the _ underscore symbol in this kind of loop. The _ symbol denotes that the loop body is not using items of this sequence, the loop is used to iterate.
for _ in range(5):
print("Hello")