Tuesday, June 11, 2019

Python for Loop With Examples

In Python programming language there are two loops for..in loop and while loop. In this tutorial you’ll learn about for loop in Python is used to iterate over a sequence (like string, list, tuple).


Syntax of Python for loop

for var in sequence:
 for loop body
else:
 else_suite

All the elements in the sequence are iterated one by one using the for loop, in each iteration element is assigned to the “var” and the for loop body is executed.

The for loop in Python also includes an optional else clause.

for loop flow

Python for Loop

Python for loop examples

1- If you want to display characters of a String using for loop in Python.

str = 'Test'
for ch in str:
    print(ch)

Output

T
e
s
t

2- Display all the elements in a list using for loop in Python.

cities = ['New York', 'London', 'Mumbai', 'Paris', 'Madrid']
for city in cities:
    print(city)

Output

New York
London
Mumbai
Paris
Madrid

for loop with range sequence type

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

Syntax of range is-

range([start,] stop[, step])

If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0.

1- Iterating 0..9 using range and for loop.

for i in range(10):
    print(i)

Output

0
1
2
3
4
5
6
7
8
9

Since start and step arguments are omitted in the range so by default step is 1 and start is 0.

2- Display odd numbers between 1 and 10 using range and for loop in Python.

for i in range(1, 10, 2):
    print(i)

Output

1
3
5
7
9

Here start argument is 1 and step is 2.

3- To display all the elements in a list using index.

Using len function you can get the total number of elements in the list which becomes an argument for range.

cities = ['New York', 'London', 'Mumbai', 'Paris', 'Madrid']
for i in range(len(cities)):
    print(cities[i])

Output

New York
London
Mumbai
Paris
Madrid

Python for loop with else statement

In Python for loop has an optional else statement too. If the for loop runs till completion and terminates the else-suite is executed.

If for loop doesn’t run completely because of any of the following reason, else statement is not executed.

  • for loop is terminated abruptly due to a break statement
  • for loop is terminated abruptly due to a return statement
  • if an exception is raised

Here is an example showing a scenario where for loop with else statement can come handy. If you want to implement a functionality to find an element in array. If element is found in the array then its index is returned otherwise -1 is returned.

In this scenario you can use else statement with python for loop. If an element is found you will return its index so else suite won’t be executed. If for loop runs till completion that would mean searched element is not found in the array in that case else suite is executed and -1 is returned.

from array import *
def find_in_array(array, value):
    for index, e in enumerate(array):
        if e == value:
            return index
    # else associated with for loop
    else:
        return -1

a = array('i', [3,4,5,6,7])
find_value = 4
index = find_in_array(a, find_value)
if index != -1:
    print(find_value, 'found in array at index', index)
else:
    print(find_value, 'not found in array')

Output

4 found in array at index 1

Nested for loop

for loop can be nested which means you can have one for loop inside another. In the nested loops for each iteration of the outer for loop, inner for loop is iterated for the given range of elements.

Python Nested for loop example

In the example a pyramid pattern using * is displayed using nested for loops.

rows = 6
for i in range (1, rows):
    for j in range (0, rows -i):
        #print spaces, end='' ensures control 
        # remains on the same line
        print(' ', end='')
    for k in range (0, i):
        print('* ', end='')
    print()

Output

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

Though in Python same pyramid pattern can be displayed very elegantly using a single for loop.

rows = 6
for i in range (1, rows):
    #repeat space for given times 
    print(' '*rows, end='')
    print('* '*(i))
    rows = rows -1

That's all for this topic Python for Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Conditional Statement - if, elif, else Statements
  2. Python return Statement With Examples
  3. Python break Statement With Examples
  4. Method Overriding in Python
  5. Name Mangling in Python

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Nonlocal Keyword in Python With Examples
  3. String Slicing in Python
  4. Python Exception Handling Tutorial
  5. Association, Aggregation And Composition in Java
  6. Why Class Name And File Name Should be Same in Java
  7. Just In Time Compiler (JIT) in Java
  8. BeanFactoryPostProcessor in Spring Framework

No comments:

Post a Comment