Python - for loop

The for loop is a generic iterator in python, it can step through the items in any ordered sequence or other iterable object.

Python implements an iterator-based ‘for loop’. It is a type of ‘for loop’ that iterates over a list of items through an explicit or implicit iterator.

The loop is introduced by the keyword ‘for’ which is followed by a random variable name which will contain the values supplied by the object.

The Python for loop begins with a header line that specifies an assignment target, along with the object you want to step through.

Syntax

for iterating_var in sequence:
   statements(s)

 

Flow Diagram

 

for loop in Python

 

Example

sum = 0
for x in [1, 2, 3, 4]:
   sum =sum + x
print sum

Output

 10