Python For Loop Examples

How and when do I use for loops under Python programming language? How can I use the break and continue statements to alter the flow of a Python loop?

Tutorial details
Difficulty Easy (rss)
Root privileges No
Requirements Python
Time 10m
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. This page explains the basics of the Python for loop in including break and continue statements.

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
Here is what we see:

Welcome 1 times
Welcome 2 times
Welcome 3 times

Above example can be written using while loop as follows:

#/usr/bin/python
i=1
while i <= 3:
	print("Hello World,",i," times.")
	i += 1

Modified outputs:

Hello World, 1  times.
Hello World, 2  times.
Hello World, 3  times.

Anopther Python 3 for loop example which prints common Linux distro names:

#!/usr/bin/python3
distros = ["RHEL", "Fedora", "Debian", "Ubuntu", "Arch", "Alpine"]
 
for d in distros:
  print("Linux distro name: " + d)

When executed we will see:

Linux distro name: RHEL
Linux distro name: Fedora
Linux distro name: Debian
Linux distro name: Ubuntu
Linux distro name: Arch
Linux distro name: Alpine

Nested for loop example

The following code shows classic nested for loop using python:

#!/usr/bin/python
# Python 2.x version
# 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

Python 3.x version:

#!/usr/bin/python3
# Nested for loop example
 
### Outer for loop ###
for x in range(1,5 ):
    ### Inner for loop	 ###
    for y in range(1, 5):
        print('%d ' % (x),  end = '')
    print("")

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

*** 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 under Python 2.x:

#!/usr/bin/python
# Only works with Python 2.x
# There no xrange() function in Python3
# 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 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)

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)

Now here is what we see:

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 (location),value (nameserver) using dict data type
for location in dnsservers:
    print(dnsservers[location], "dns server is located in", location )

Sample outputs:

ns1.cyberciti.com dns server is located in us
ns2.cyberciti.biz dns server is located in uk
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 via Python raw_input/input():

#!/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 = input("Provide geo location ")
#print(search_ns_location)
#exit(0)
 
for location in dnsservers:    
    if location == search_ns_location:
        print(dnsservers[location], "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.")

Session:

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

Provide geo location nyc nyc not a valid geo location.

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
#!/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)

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
#!/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 session:

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

continue statement

The continue statement allows the code to exit the current iteration. I will not terminate your Python for-loop. In other words, we can use the continue statement to skip the current iteration when a particular condition met:

#/usr/bin/python3 
distros = ["RHEL", "Fedora", "Debian", "Ubuntu", "Arch", "Alpine"]
 
# skip for loop when distro name (d) is equal to Debian  #
for d in distros:
    if d == "Debian":
        continue
    print("Linux distro name: " + d)

else statement

The else is used when you want to do something when all iterables are exhausted. This is an optional clause. For instance:

#!/usr/bin/python3
for os in ["macOS", "Linux", "Windows10", "FreeBSD", "Unix"]:
    print("OS: ", os)
else:
  print('OS loop list completed. Bye!')

Summing up

You learned about Python for loop syntax and various examples. Now you can regularly execute a block of code a fixed number of times using for loop. See Python documentation for further info.


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 11 comments so far... add one

CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
11 comments… add one
  • Hest Jun 2, 2014 @ 3:33

    Nice

  • krish Jun 16, 2015 @ 23:41

    hi, can u explain above nested for loop example line by line ?

  • Anamika Dec 4, 2015 @ 16:00

    How can we write for loop for two variables like in c :
    for(int i =0,j=0;i>5,j>8;i–,j–)

  • tsigabu Jan 18, 2016 @ 13:55

    how to create shows below program in c++ using loop

    ***********
    ** **
    ***********
    ** **
    ***********

  • Luis Feb 9, 2016 @ 23:26

    You could add some info about List Comprehensions.https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions.
    Although it would be a combination of for loop, lists assignation and iteration

  • vaisakh Apr 10, 2016 @ 6:28

    for a[i[ in a:

    what does it mean, when a is a list.

  • siddharth Jul 6, 2016 @ 12:51

    a better looping eg should be given

  • sandeep Oct 26, 2016 @ 11:53
    x = 1
    for letter in 'word':
        print(x)
        x + = 2
    

    this is m program but when i run it it show some error.

    a@a-HCL-Desktop:~$ python foror.py
      File "foror.py", line 1
        x = 1
        ^
    IndentationError: unexpected indent
    a@a-HCL-Desktop:~$
    
    • 🐧 Vivek Gite Oct 26, 2016 @ 19:08

      This error means you have mixed tabs and spaces. Run it as follows to find out of IndentationError
      python -t foror.py
      Use programming editor such as as vim or emacs to avoid such errors.

  • Shilpa Mar 2, 2021 @ 19:36

    nice to see all examples are works with Python 3

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Problem posting comment? Email me @ webmaster@cyberciti.biz