Python

Python For Loop

Python For Loop
Written by ProgrammingPot

In this tutorial, you will learn about Python for loop used for the iteration of a block of code over a sequence including Python lists, tuple, string, and dictionary.

In Python, there are two types of loops only.

Python For Loop


Python for loop is used for repeated execution of a group of statements for the desired number of times. It iterates over the items of lists, tuples, strings, the dictionaries and other iterable objects.

For loop’s basic mechanism is like:

For all items in a list or sequence, keep doing this

Python for loop syntax

for var in sequence:
    statement(s)

Where,

  • var = Variable that holds the value of the item in the sequence in each iteration
  • sequence = A sequence of values assigned to var in each iteration
  • statements = Code to be executed until for loop terminates

As seen in syntax, a Python for loop starts with a keyword for, followed by a variable that holds the value of items in the sequence we iterate over. The sequence can be list, tuple, string, dictionary or any other iterable object.

Flowchart of Python for loop

Python For Loop

As seen in flowchart above, in for loop, first it is checked whether or not we have reached the last item in the sequence. If not, the body of for loop is executed again else the flow of program jumps out of for loop.

Python for loop example 1: Iterating over a list

In the following example, for loop will iterate through list py_list and print each item in the list.

#list of items
py_list = ['Apple','Mango','Guava','Pineapple']
i = 1

#Iterating over the list
for item in py_list:
  print ('Item ',i,' is ',item)
  i = i+1

Output

Item 1 is Apple
Item 2 is Mango
Item 3 is Guava
Item 4 is Watermelon

Python for loop example 2: Iterating over a Tuple

In the following program, for loop will iterate over the tuple of first four prime numbers and print them one by one.

#Tuple of items
tuple_prime = (2,3,5,7)

print ('These are the first four prime numbers ')
#Iterating over the tuple
for item in tuple_prime:
  print (item)

Output

These are the first four prime numbers
2
3
5
7

Python for loop example 3: Iterating over a String

In the following program, for loop will iterate over the string and print each character in that string.

#declare a string to iterate over
py_string = 'YOLO'

#Iterating over the string
for letters in py_string:
  print (letters)

Output

Y
O
L
O

Python for loop example 4: Iterating over a dictionary

In the following program, for loop will iterate over the dictionary ‘bikes’ containing company name as key and motorbike model as value and print keys and values.

#creating a dictionary
bikes = {"Royal_Enfield":"Continental","Kawasaki":"Ninja","Yamaha":"R1"}

#Iterating over the dictionary to print keys
print ('Keys are:')
for keys in bikes:
  print (keys)

#Iterating over the dictionary to print values
print ('Values are:')
for models in bikes.values():
  print(models)

Output

Keys are:
Royal_Enfield
Kawasaki
Yamaha
Values are:
Continental
Ninja
R1

Note: If we don’t mention explicitly bikes.values( ) by default the program will always iterate and print only keys instead of values.

So far in this article, we learned about using for loops iterating over a sequence of list, tuple, string, and dictionary.Now let’s discuss a Python function

Now let’s discuss a Python function called range( ) used for generating a range of numbers and how it is used in Python for loops.

The range( ) function


The range( ) is a built-in Python function used for iterating over a sequence of numbers.

Here is how we can use range function.

range(n)
range(x,y)
range(start,end,step_size)

Where,

  • range(n)  will generate numbers from 0 to (n-1)
  • range(x,y) will generate numbers from x to (y-1)
  • range(start,end,step_size) will generate numbers from start to end with step_size as incremental factor in each iteration. step_size is default if not explicitly mentioned.

Example of range( ) function

Python For Loop

This is how range( ) function works in Python. Now let’s use range( ) function in for loop to iterate over a sequence of numbers.

Example: Python for loop and range( ) function

#simple for loop using range()
for x in range(4):
 print x

#for loop to iterate over a list using range()
py_list = ['Soccer','Cricket','Golf']
for item in range(len(py_list)):
  print (py_list[item],' is a outdoor sport.')

Output

This script will generate following output.

0
1
2
3
Soccer is outdoor sport.
Cricket is outdoor sport.
Golf is outdoor sport.

In above program, len( ) is a built is a built-in python function to calculate length. So we have used len( ) to iterate through list using indexing.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.