ScanSkill

for loop

for loop is used to iterate over elements of an iterable or sequence(i.e. list, tuple, dictionary, set, or string).

Syntax

for item in iterable:
    statement(s)
else:
    statement(s)

Here,

  • for: starts a for loop.
  • item: Individual item on each iteration. This variable is bound to the current element of the iterable.
  • in: Separates items from each other.
  • iterable: An iterable object. List, dictionary, set, tuple, or string.
  • statement(s): Block of code to be executed.
  • else: Optional. Used to indicate the block of code to be executed when the loop terminates without break statement.

Note: When looping, after each iteration, the next item is retrieved from the iterable. The loop’s statement(s) will be continuously executed until the iterable container is empty.

Python has only one for loop, which is functionally the same as for each in some other languages. To loop a specified number of times range() or xrange() function is used.

Examples

>>> for i in range(7):
...     print i
...
0
1
2
3
4
5

You can also iterate over files with a for loop:

>>> for line in open("/home/sagar/example.txt):
...     print line
...
line 1
line 2
line 3
  • With else condition(break statement in for loop)
>>> for i in range(3):
...     print i
... else:
...     print("No break is used.")
...
0
1
2
No break is used.

In the following example, else condition won't be executed as there is break statement used in for.

>>> for i in range(3):
...     print(i)
...     break
... else:
...     print("Break used")
... 
0