Python programming language provides the for
loop in order to iterate over a given sequence, list, items, string, array, tuple, dictionary, etc. Even there are different ways to loop like while loop. In this tutorial, we examine how to loop over different items and data types like sequence, list, string, tuple, and dictionary.
for Loop Syntax
The for loop has very simple syntax according to the other programming languages like C#, PHP, C, C++, etc. The for loop syntax is like below.
for ITEM in SEQUENCE:
CODE
- ITEM is a variable that contains a value in each step or iteration which is provided by SEQUENCE.
- SEQUENCE is a list, array, string, tuple, etc. which contains single or multiple items in an iterable way.
- CODE is the loop body that is used to process the ITEM and make other operations. The CODE part can be single or multiple lines and instructions.
Iterate over List
One of the most popular use cases of the for loop is iterating over the list or list data type. Python list is the implementation of the arrays in other programming languages like JavaScript, C#, C, C++, etc. In the following example, we will iterate over the given list named cities and print every city which is an item in the code part of the for loop.
cities = [ 'london' , 'istanbul' , 'california' , 'barcelona' ]
for city in cities:
print("City name is "+city)
The output will be like the below. We can see that every list item which is strings is iterated in each step and set into the variable named city. The city variable can be only used in this loop not outside of the loop.
City name is london City name is istanbul City name is california City name is barcelona
Iterate over String Character By Character
Strings are special data types which are consist of single or multiple characters. Even though they may seem like a single variable or value they consist of multiple characters. So Python string is an iterable type where multiple characters can be iterated with the for loop.
sentence = "I like pythontect.com"
for char in sentence:
print(char)
The output will be like the below. We can see that every character is set into the variable named char and this char variable content is printed line by line. Even space character is printed too.
I l i k e p y t h o n t e c t . c o m
Iterate over Tuple
The tuple is another data type specifically used in Python. The tuple is very similar to the list but the content of the tuple can not be changed. Tuple data type is a sequence or iterable and loop with the for like below.
cities = ( 'london' , 'istanbul' , 'california' , 'barcelona' )
for city in cities:
print("City name is "+city)
The output will be like the below.
City name is london City name is istanbul City name is california City name is barcelona
Iterate over Dictionary
Dictionary is a special data type that contains key/value pairs in order to store keys and values in a single item which works like a real-life dictionary. Dictionary is a sequence type that can be iterable and iterated with the for loop. Only the key is iterated with the for loop.
numbers = { '1':'one' , '2':'two' , '3':'three' }
for number in numbers:
print("Key is "+number)
The output will be like the below. which is the key of the key/value pair.
Key is 1 Key is 2 Key is 3
If we want to also access the value of the dictionary item in a for loop we need to use the current key to get the current value.
numbers = { '1':'one' , '2':'two' , '3':'three' }
for number in numbers:
print("Key is "+number)
print("Value is "+numbers[number])
Output is like below the key is the first line and the value is the second line.
Key is 1 Value is one Key is 2 Value is two Key is 3 Value is three
Iterate over Number Range or range() Method
range()
is a method used to create a sequence of numbers in an easy and practical way. For example, if you want to iterate from 1 to 100 using for loop it is very hard to use a list or write all numbers from 1 to 100. The range() method can be used to specify the start and end of the number list. By default increment value is 1. Optionally the increment value can be also provided which will be different than 1.
for number in range(0,100):
print("Number is "+str(number))
The output will be like the below.
Number is 0 Number is 1 Number is 2 Number is 3 Number is 4 Number is 5 Number is 6 Number is 7 Number is 8 ... Number is 99 Number is 100
We can also set the increment value for the range() method like below. We will set the increment value as 3.
for number in range(0,99,3):
print("Number is "+str(number))
The output will be like the below.
Number is 0 Number is 3 Number is 6 Number is 9 Number is 12 Number is 15 Number is 18 Number is 21 Number is 24 Number is 27 ... Number is 96 Number is 99
continue Statement
By default, every step will be evaluated in the for loop in Python. If we need to skip a single or more iteration or step we can use the continue
statement. This will skip or jump to the next step.
for number in range( 0 , 10 ):
if number == 3:
continue
print("Number is "+str(number))
The output is like below where the number 3 is skipped with the continue statement.
Number is 0 Number is 1 Number is 2 Number is 4 Number is 5 Number is 6 Number is 7 Number is 8 Number is 9
break Statement
If you want to end the for loop completely without continuing iteration and skipping the next items the break
the statement can be used.
for number in range( 0 , 10 ):
if number == 3:
break
print("Number is "+str(number))
The output will be like below where the iteration will stop after printing number 2 in the number 3.
Number is 0 Number is 1 Number is 2
Nested for Loops
Multiple for loops can be used inside each other. This is called nested for loops which can be very useful for multilevel lists or matrixes etc. Actually, there is no difference from the single for loop where multiple for loops will be put inside another for loops according to the algorithm.
for x in range(0,10):
for y in range(0,10):
print("Number is "+str(x)+str(y))
The output will be like the below.
Number is 00 Number is 01 Number is 02 Number is 03 Number is 04 Number is 05 Number is 06 Number is 07 Number is 08 ... Number is 98 Number is 99