How Python for loop works

Python for loop Syntax:

How Python for loop works

for loop in any language has almost the same syntax but in Python, it is slightly different.

for var in seq:
 condition or statement
  • here seq is any sequence that can be generated from any iterator object.

  • iterator objects in Python are those objects over which a loop can be iterated.

  • in python, everything is an object, all data types like string, integer, list, tuple, dictionary, float, and set can give you different classes of objects.

  • from these classes- list, tuple, dictionary, set, and string can provide you with the iterator objects, whereas integer does not provide iterator objects.

  • in the last, in for loop either we can provide a condition or a statement of a code which says that what needs to be done.

  • Let's take some examples and understand this.

    Example-1: loop over a string.

      st="kapil"
      for var in st:
        print(var)
    
      #Result
      k
      a
      p
      i
      l
    

    Example-2: loop over a list.

  •     ls=[1,2,3,4,5]
        for var in ls:
          print(var)
    
        #Result
        1
        2
        3
        4
        5
    

    Example-3: loop over a set.

  •     s={1,2,4,5}
        for var in s:
          print(var)
        #Result
        1
        2
        3
        4
        5
    

    Example-4: loop over a dictionary.

  •     d={'name':kapil,'id':101,'city':Delhi}
        for key,value in d.items():
           print("Key:", key,end="") 
           print("Value:" ,value)
        #Result
        name: kapil
        id: 101
        city: Delhi