In this post is covered the usage of for loop in several situations:

  • basic usage
  • python for loop skipping step
  • looping over list with for loop
  • how to loop over dictionary
  • how to simulate for loop with while in python

For loop basic

The most simple usage of for loop in general is to iterate over range of numbers. In this example we iterate over numbers from 0 to 9

for i in range(0, 10):
    print(i, end=' ,')

result:

0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,

For loop skip step

If you want to skip steps in for loop then you can do it by using continue. In the example below we are iterating from 0 to 9 printing only odd numbers. The second example skips exactly 3, 5 and 8 elements:

for i in range(0, 10):
    if i % 2:
        continue
    print(i, end=' ,')
    
for i in range(0, 10):
    if i in (3, 5, 8):
        continue
    print(i, end=' ,')

result:

0, 2 ,4 ,6 ,8 ,
1 ,2 ,4 ,6 ,7 ,9

In some situation could be better to use while loop for skipping steps:

i = 1
while i < 10:
    if i == 2:
        i = 7
    print(i, end=' ,')
    i += 1

result:

,1 ,7 ,8 ,9 ,

For loop over list

Looping over list with for is done by using keyword in:

people = ["James", "Xie", "Ann", "David"]
for p in people:
    print(p, end=' ,')

result:

James ,Xie ,Ann ,David ,

For loop and dictionary

Iterating over dictionary you can access:

  • keys only
  • values only
  • keys and values
score = {'James': 14.1, 'David': 14.3, 'Ann': 15.2, 'Boris': 15.3}

# print only keys
for sc in score:
    print(sc, end=' ,')

# print only values
for sc, val in score.items():
    print(val, end=' ,')

# print keys and values
for key, value in score.items():
    print("key : {0}, value : {1}".format(key, value), end=' ,')

result:

James ,Boris ,Ann ,David ,
15.3 ,15.2 ,14.1 ,14.3 ,
key : James, value : 14.1 ,key : Boris, value : 15.3 ,key : Ann, value : 15.2 ,key : David, value : 14.3 ,

Simulate for loop with while

Looping over list with for is done by using keyword in:

n = 0
while n < 5:
    print(n, end=' ,')
    n += 1

result:

,0 ,1 ,2 ,3 ,4