Python For Loop
Python For loop is used to execute a set of statements iteratively over a sequence of elements.
In this tutorial, we will learn the syntax of For Loop, and cover examples with For Loop where For Loop is used to iterate over different types of sequences and collections in Python.
We shall also discuss Nested For Loop in this tutorial.
The syntax of For Loop in Python is
for <variable> in <iterable>: statement(s)
where an iterable could be a sequence or collection or any custom Python class object that implements __iter__() method.
The flow of program execution in a Python For Loop is shown in the following picture.
For Loop with List
In this example, we will take a list of numbers and use for loop to iterate over each of the element in this list.
myList = [1, 2, 3, 5, 6, 10, 11, 12] for item in myList: print(item)Try Online
1 2 3 5 6 10 11 12
For Loop with Range
In this example, we will take a range object, and use for loop to iterate over each number in this range.
myRange = range(1, 5) for number in myRange: print(number)Try Online
1 2 3 4
For loop with String
In this example, we will take a String and use for loop to iterate over each character of the string.
myString = 'tutorialkart' for ch in myString: print(ch)Try Online
t u t o r i a l k a r t
For loop with Tuple
In this example, we will take a tuple and use for loop to iterate over each item in the tuple.
myTuple = ('abc', 'bcd', 'xyz') for item in myTuple: print(item)Try Online
abc bcd xyz
Nested For Loop
Any statement inside the for loop could be another for loop, if block, if-else block or any such.
An example program for nested for loop with embedded if-else blocks is given below.
for greeting in ['hello', 'hi', 'hola']: for ch in greeting: print(ch) if greeting=='hello': print("hello buddy!") else: if greeting=='hi': print("hi friend!") else: print("hola gola!")Try Online
h e l l o hello buddy! h i hi friend! h o l a hola gola!
In this Python Tutorial, we have learn about for loop execution flow, for loop syntax in python, nested for loop, for loops that iterate over list, range, string and tuple. As an exercise, try out the for loop that iterates over buffer.