In Python, we use a for loop to iterate over sequences such as lists, strings, dictionaries, etc.
For loop in one line
Using for loop without accessing sequence items
If we don’t intend to use items of sequence inside the body of a loop, it is clearer to use the _
(underscore) as the loop variable. For example,
# iterate from i = 0 to 3
for _ in range(0, 4:
print('Hi')
0
1
2
3
Here, the loop runs four times. In each iteration, we have displayed Hi
. Since we are not using the items of the sequence(0, 1, 2 and 4) in the loop body, it is better to use _
as the loop variable.
Reference: