DEV Community

Cover image for Python for loop

Posted on

Python for loop

In the Python programming language, the for loop is often used to repeat code. Another word for "repeat code" is iteration.

Other than iterating over code, a for loop can iterate any sequence of items, such as a list or a string.


for loop syntax is as follows:

   for iterating_var in sequence:
       statements (s)

flow chart:

The control flow graph shows the execution of a for loop

python for loop


#-*- coding: UTF-8 -*-

for letter in 'Python': # first instance
   print('current letter:', letter)

fruits = [ 'banana', 'apple', 'mango']
for fruit in fruits: # second instance
   print('current letter:', fruit)

print("Good bye!")

Examples of the above output:

current letter: P
current letter: y
current letter: t
current letter: h
current letter: o
current letter: n
current letter: banana
current letter: apple
current letter: mango

by an iterative sequence index

You can traverse through the execution cycle by index, the following examples:

#-*- coding: UTF-8 -*-

fruits = [ 'banana', 'apple', 'mango']
for index in range(len(fruits)):
    print("Current fruit:", fruits[index])

print("Good bye!")

Examples of the above output:

Current fruit: banana
Current fruit: apple
Current fruit: mango
Good bye!

The above examples we use the built len() function and range(), len() function returns the length of the list, i.e. the number of elements. range returns a sequence number.

Other examples

Print a triangular array 1-9:

# - * - coding: UTF-8 - * -

for i in range (1,11):
    for k in range (1, i):
        print(k, end=''),
    print("\n", end='')

Example of the above output:


You can also use a for loop on a dictionary, but this works a bit differently:

d = {'x': 1, 'y': 2, 'z': 3} 
for k,v in d.items():
    print(k, 'corresponds to', v)

Top comments (0)