Python For Loop Examples

by on November 15, 2011 · 0 comments· LAST UPDATED December 9, 2013

in , ,

How and when do I use for loops under Python programming language?

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsPython
Estimated completion time10m

A for loop is a Python statement which repeats a group of statements a specified number of times. You can use any object (such as strings, arrays, lists, tuples, dict and so on) in a for loop in Python.

Python for loop syntax

The basic syntax is:

 
 
for var in list:
   statement-1
   statement-2
   statement-N
 
 

Where,

  1. var : var reads each element from the list starting from the first element.
  2. list : list is a Python list i.e. a list or a string.

Examples and usage in Python

The following example illustrates the use of the for statement in python. Create a file called for-loop.py:

 
#!/usr/bin/python
#
# for-loop.py: Sample for loop to print welcome message 3 times
#
for i in '123':
        print "Welcome",i,"times"
 
 

Save and close the file. Run it as follows:
$ chmod +x for-loop.py
$ ./for-loop.py

OR
$ python for-loop.py
Sample outputs:

Welcome 1 times
Welcome 2 times
Welcome 3 times

Nested for loop example

The following code shows classic nested for loop using python:

 
#!/usr/bin/python
# Nested for loop example
 
### Outer for loop ###
for x in xrange(1,5 ):
    ### Inner for loop	 ###
    for y in xrange(1, 5):
        print '%d ' % (x),
    print
 

Sample outputs:

Fig.01: Nested Python for loop program output

Fig.01: Nested Python for loop program output

Iterating python for loop using range() function

Instead of using a string called '123', try range() to iterate over a sequence of numbers:

 
#!/usr/bin/python
# Python for loop using range()
 
print "*** Generates a list of 3 values starting from 0 ***"
for i in range(3):
        print "Welcome",i,"times."
 
print "*** Generates a list of 3 values starting from 1 ***"
for i in range(1,4):
        print "Welcome",i,"times."
 

Sample outputs:

*** Generates a list of 3 values starting from 0 ***
Welcome 0 times.
Welcome 1 times.
Welcome 2 times.
*** Generates a list of 3 values starting from 1 ***
Welcome 1 times.
Welcome 2 times.
Welcome 3 times.

It is recommended that you use the xrange() function to save memory:

 
#!/usr/bin/python
# Python for loop using range()
 
print "*** Generates a list of 3 values starting from 0 using xrange() ***"
for i in xrange(3):
        print "Welcome",i,"times."
 
print "*** range() vs xrange() ***"
print "range() creates a list containing numbers all at once."
print "xrange() creates a list containing numbers as needed."
 

Python for loop List example

The following example illustrates the use of the for statement using a list:

 
#!/usr/bin/python
# Sample for loop using a List
 
## define a list 
shuttles = ['columbia', 'endeavour', 'challenger', 'discovery', 'atlantis', 'enterprise', 'pathfinder' ]
 
## Read shuttles list and store the value of each element into s and display on screen
for s in shuttles:
        print s
 

Sample outputs:

columbia
endeavour
challenger
discovery
atlantis
enterprise
pathfinder

To print index and its value, try enumerate(). It simplify a commonly used looping methods. It provides all iterable collections with the same advantage that iteritems() affords to dictionaries -- a compact, readable, reliable index notation:

 
#!/usr/bin/python
# A list of shuttles 
shuttles = ['columbia', 'endeavour', 'challenger', 'discovery', 'atlantis', 'enterprise', 'pathfinder' ]
 
## Read shuttles list and enumerate into index and value 
for index, value in enumerate(shuttles):
        print index, value
 

Sample outputs:

0 columbia
1 endeavour
2 challenger
3 discovery
4 atlantis
5 enterprise
6 pathfinder

Dictionary data type example using for loop

Dictionaries are indexed by keys. You can use key and value pair using a Python for loop. The following example illustrates this concept:

 
#!/usr/bin/python
 
# define a dict data type for our dns server as geoLocation : DNS server name
dnsservers = {"us":"ns1.cyberciti.com", "uk":"ns2.cyberciti.biz", "asia":"ns3.cyberciti.org"  }
 
# Python for loop for key,value using dict data type
for location, server in dnsservers.iteritems():
	print server, "dns server is located in" , location
 

Sample outputs:

ns2.cyberciti.biz dns server is located in uk
ns1.cyberciti.com dns server is located in us
ns3.cyberciti.org dns server is located in asia

The following example iterates through dictionary data type and only display the result if the match is found:

 
#!/usr/bin/python
## Dict data type
dnsservers = {"us":"ns1.cyberciti.com", "uk":"ns2.cyberciti.biz", "asia":"ns3.cyberciti.org"  }
 
## Is location found ? 
found = False
 
## INPUT: Search for a geo location 
search_ns_location = raw_input("Provide geo location ")
 
## Use for loop to search geo location for ns
for location, server in dnsservers.iteritems():
	if location == search_ns_location:
		print server, "dns server is located in" , search_ns_location
		found = True
 
## Display an error 
if found == False :
	print search_ns_location ,"not a valid geo location."
 

Sample outputs:

Provide geo location asia
ns3.cyberciti.org dns server is located in asia

Provide geo location nyc nyc not a valid geo location.

How do I use for as infinite loops?

An infinite for loop can be created with while True: syntax:

#!/usr/bin/python
# Use while loop as follows to run from 1 (i=1) to infinity
# The following will run infinity times 
i=1
while True:
	print "Welcome", i, "times. To stop press [CTRL+C]"
	i += 1
 

You can add delay using sleep() as follows

#!/usr/bin/python
# Use while loop as follows to run from 1 (i=1) to infinity
# The following will run infinity times 
import time
i=1
while True:
	print "Welcome", i, "times. To stop press [CTRL+C]"
	i += 1
        # Delay for 2 seconds
        time.sleep(2)
 

Sample outputs:

Fig.02: Infinite for loop program output

Fig.02: Infinite for loop program output

Conditional exit with break

You can do early exit with break statement inside the for loop. The syntax is:

for condition:
    if condition is true:
        break

Early exit example:

#!/usr/bin/python
# Use while loop as follows to run from 1 (i=1) to infinity
# The following will run infinity times 
import time
i=1
while True:
	print "Welcome", i, "times. To stop press [CTRL+C]"
	i += 1
        #### Delay for 2 seconds ####
        time.sleep(2)
        #### Die (early exit) if i is 5 ####
        if i == 5:
             print "Early exit detected...terminating infinity"
             break
 

Sample outputs:

Welcome 1 times. To stop press [CTRL+C]
Welcome 2 times. To stop press [CTRL+C]
Welcome 3 times. To stop press [CTRL+C]
Welcome 4 times. To stop press [CTRL+C]
Early exit detected...terminating infinity
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: , , , ,

Previous Faq:

Next Faq: