Using loop list in Python

Using loop list in Python can be the same procedure as other programming languages but they have different  syntax.

Loop in Python can be used keyword While & For. In this page I will only brief explain For and While loop that using with list.

  • For loop
myCar=['Toyota', 'Mitsubishi','Volvo']
for x in myCar:
    print(x)
    #exit()
'''output:Toyota
          Mitsubishi
          Volvo'''

Print(x) has to be increase indent from For, otherwise I will getting error.

  • While loop
myCar=['Toyota', 'Mitsubishi','Volvo']
x=0
while x <len(myCar):
    print(myCar[x])
    x=x+1
    #exit()
'''output:Toyota
          Mitsubishi
          Volvo'

In while loop, x must be declare before using with condition. 

    myCar[x] index to seek any position of elements in list. So they will output item according to x until x greater than the length of list, then loop will  end.

  • Looping with index number by using range and len keyword
myCar=['Toyota', 'Mitsubishi','Volvo']
for x in range(len(myCar)):
    print(myCar[x])
'''output:Toyota
          Mitsubishi
          Volvo''' 

Loop to range of list is referring to the length myCar by len. The range will know the length in this list, So loop continues repeating until the end of length in list and then, loop end.

freecode4learn.com

Leave a Reply