for loop in python

  • 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.
  • Sometimes we want to loop through a set of things such as a list of words, the lines in a file, or a list of numbers.
  • When we have a list of things to loop through, we can construct a definite loop using a for statement.
  • We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.
  • 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