In this post, you will see and learn the usage of for loop in Python with examples. Here, we’ll mainly focus on iterating the list object using the “for loop” construct in different ways.
The lists in Python are hybrid data structures that can hold a variety of values. We’ll try to demonstrate the use of a for loop to traverse a sequence with the help of examples.
Prior to reading this post, it is advisable that you know how the for loop works in Python. It will help you learn the lopping basics and techniques for fast traversing.
For Loop Examples in Python
You have read about Python for loop in our previous tutorials. It is much more flexible than the loops available in other languages. You can apply them to perform interesting programming tasks.
Let’s check out some examples:
Traverse a list of different items
It is one of the most common examples where Python for loop can be used. Say, you have a list that contains strings and numbers. And you have to iterate each element one by one.
So, you should be using the for loop in the following manner:
#Initialize a sequence elements = ["Python", 3, 8, "CSharp", "PHP"] #for each element in the list, iterate the list for ele in elements: # print the element print((ele), end = " ")
Output
Result... Python 3 8 CSharp PHP CPU Time: 0.02 sec(s), Memory: 8328 kilobyte(s)executed in 0.652 sec(s)
Iterate the list from end using for loop
In this section, we’ll see how to print each item on the list in reverse order. To do so, you can follow one of the methods given below.
Using the reversed() function
It inverts the order of a list. Go over the below sample code.
#Prepare a list elements = ["Python", 3, 8, "CSharp", "PHP"] #Iterate the list in reverse order for ele in reversed(elements): # print the element print((ele), end = " ")
Output
Result... PHP CSharp 8 3 Python CPU Time: 0.03 sec(s), Memory: 8484 kilobyte(s)
Reverse a list in for loop using the slice operator
#Prepare a list elements = ["Python", 3, 8, "CSharp", "PHP"] #Reverse the list using slice operator for ele in elements[::-1]: # print the element print((ele), end = " ")
Output
Result... PHP CSharp 8 3 Python CPU Time: 0.04 sec(s), Memory: 8348 kilobyte(s)
Example of Python for loop to iterate in sorted order
You can also enumerate a list in the sorted order using a for loop. To do so, Python provides the sorted() function. It modifies the order of a sequence.
Check out the following sample code.
#Prepare a list of numbers elements = [11, 23, 43, 17, 32] #Run a for loop on a sorted list for ele in sorted(elements): # print the element print((ele), end = " ")
Output
Result... 11 17 23 32 43 CPU Time: 0.03 sec(s), Memory: 8480 kilobyte(s)
Using for loop to enumerate the list with index
In Python, the enumerate() function is available that you can call over a sequence and get the indexes of elements in each iteration.
Copy/paste the following code and try it out yourself.
#Prepare a list of numbers elements = [11, 23, 43, 17, 32] #Run a for loop on a sorted list for index, data in enumerate(elements): # show the index and the value stored print("Element value of {} := {}".format(str(index), str(data)))
Output
Result... Element value of 0 := 11 Element value of 1 := 23 Element value of 2 := 43 Element value of 3 := 17 Element value of 4 := 32 CPU Time: 0.02 sec(s), Memory: 8352 kilobyte(s)
Iterate multiple lists with for loop in Python
Imagine a scenario, where you have a sequence of countries and also have another list of capitals. Now, write Python code to print the summary of countries with their capital cities.
Check out the below Python for loop example to accomplish this. Here we called the Python zip function to combine multiple lists.
countries = [ 'USA', 'Germany', 'France', 'India', 'China' ] capitals = [ 'Washington, D.C.', 'Berlin', 'Paris', 'Delhi', 'Beijing'] population = [ 702000, 3570000, 2140000, 19000000, 21500000] #Consolidate three lists using the zip() function print("{0:<10} {1:<20} {2:>5}".format("#Country", "#Capital","#Population")) for country, capital, size in zip(countries, capitals, population): print("{0:<10} {1:<20} {2:>5}".format(country, capital, size))
Output
Result... #Country #Capital #Population USA Washington, D.C. 702000 Germany Berlin 3570000 France Paris 2140000 India Delhi 19000000 China Beijing 21500000 CPU Time: 0.02 sec(s), Memory: 8460 kilobyte(s)
In the above example, we used the format function with alignments to print the intuitive summary. Read the below tutorial to learn more about such formatting.
Also Check: Format strings in Python