Looping in Python3

while

while loop in python resembles the tradition C-style loop as follows. This method of looping is NOT very popular in Python although.

alphabets = ["a", "b", "c", "d", "e"]
i = 0
while i < len(alphabets):
    print(alphabets[i], end=', ')
    i += 1
a, b, c, d, e, 

range() function

The built-in function range() generates the integer numbers between the given start integer to the stop integer, i.e., It returns a range object.

print("Python range() example")
print("Get numbers from range 0 to 5")
for i in range(5):
    print(i, end=', ')

Output:

Python range() example 
Get numbers from range 0 to 5 
0, 1, 2, 3, 4,

for : range of length

In a for loop, we can iterate over a sequence of numbers produced by the range() function. First, a range corresponding to the indexes in the list (0 to len(alphabets) – 1) is created. Then, loop over this range using Python’s for-in loop

alphabets = ["a", "b", "c", "d", "e"]
i = 0
while i < len(alphabets):
    print(alphabets[i], end = ', ')
    i += 1
a, b, c, d, e, 

for : the normal way

In while loop and range-of-len methods, the purpose of indexes are to retrieve elements from the list. If indexes are not used for any other purpose, a simpler for loop can be used.

alphabets = ["a", "b", "c", "d", "e"]
for letter in alphabets:
    print(letter, end = ', ')
a, b, c, d, e, 

enumerate

If indexes are really needed, then range of length procedure can be used. But in python, there is more elegant way to do that (using enumerate() function).
Python’s built-in enumerate() function allows to loop over a list and retrieve both the index and the value of each item in the list

alphabets = ["a", "b", "c", "d", "e"]
for index, letter in enumerate(alphabets):
    print(index, letter)
0 a
1 b
2 c
3 d
4 e

zip

When we want to loop over two lists or iterators at once, Python’s zip() function can be used.

number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']

for number, string in zip(number_list, str_list):
    print(number, string)
1 one
2 two
3 three