Python For Loop Examples

by on November 15, 2011 · 0 comments· last updated at November 15, 2012

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

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsPython

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.

Syntax

The 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.

Example

The following example illustrates the use of the for statement.

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

Run it as follows:
$ ./for.py
Sample outputs:

Welcome 1 times
Welcome 2 times
Welcome 3 times

range()

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."
 

List

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
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

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
# geoLocation : DNS server name
dnsservers = {"us":"ns1.cyberciti.com", "uk":"ns2.cyberciti.biz", "asia":"ns3.cyberciti.org",  }
 
# Python for loop for key,value 
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.


You should follow me on twitter here or grab rss feed to keep track of new changes.

Featured Articles:

{ 0 comments… add one now }

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <kbd> <blockquote> <pre> <a href="" title="">

Tagged as: , , , ,

Previous Faq:

Next Faq: