Every high-level programming language provides support for loops. Loops repeat a set of instructions until a specific condition is satisfied. One of the most used loops in any language is the “for” loop. In this article, we look at all for loops in the Python programming language.
You can also check this tutorial in the following video:
2. What is a For Loop
A For loop iterates over a sequence of items. Data structures like Lists, tuples, dictionaries, sets, and strings. The basic build of a for loop is as follows:
for [iterator_name] in [list/tuple/dictionary/string/Set]: [instructions to do..]
For example, we have a sequence of numbers,
numList = [1,2,3,4,5,6,7,8,9]
We can loop through this list using the for loop as follows:
for n in numList: print(n);
3. Looping through a String
A String in Python is considered a sequence. So, we can use a for loop on a String just like on any other sequence.
3.1 A Simple loop with a string
Python considers a string as a sequence of characters. So, if we run a for loop over a string and print it, Python returns each character separately. These include whitespaces. A simple example
string_name = "We forge the chains we wear in life." for char in string_name: print(char) print("\n")
We can output the characters in one line as follows:
for char in string_name: print(char, end= ' ')
3.2 For loop with enumerate
The for loop in Python iterates over a sequence. It does not keep a count of the iterator or the index. Python has an in-built function called enumerate to ease this task. Enumerate takes two parameters: the sequence and an option start.
Consider an example where we want to print out only the characters having even index. For this example, we would need the enumerate function.
inputString = "To be or not to be, that is the question" for index,str in enumerate(inputString): if index%2 ==0: print(str, end =' , ')
3.3 For loop in reverse order
We can also loop through a String in Python in reverse order. There are two ways of doing so. The first method is to slice the string in the reverse order and then loop through it. The second method is to use the reversed function.
inputString1 = “There is nothing in the world so irresistibly contagious as laughter and good humor.” #Method 1 print("For Loop with reverse string with slicing") print("\n") for c in inputString1[ : :-1]: print(c, end =' , ') print("\n") #Method 2 #length of string str_length = len(inputString1) #using reversed function print("For Loop with reverse string with reversed") print("\n") for ch in reversed(range(0, str_length)): print(inputString1[ch],end=' , ') print("\n")
3.4 For loop with a specific set of elements in a String
We can run a for loop over a specific slice of a string or a sequence. We can do so as follows:
input_string2 = "Laughter is the sun that drives winter from the human face." print("For loop with string") print("\n") for chr in input_string2[0:41:2]: print(chr, end =' , ') print("\n")
4. For loop over ranges
A range is a data structure that creates a sequence of consecutive elements. It takes two parameters, a start index and an end index, and builds a sequence by including the start index and excluding the end index. We can loop through such a range. We see an example where we use a range of 1 to 20 and print whether the number is even or odd.
for i in range(1,21): if i%2 !=0: print(i," is even.") else: print(i, " is odd")
5. For loop with a break statement
We can use a break statement with the for loop to come out of the loop when a specific condition is satisfied. The break statement makes Python quit the loop entirely. For example:
input_string3 = “He who opens a school door, closes a prison.” for str in input_string3: if str == ",": break else: print(str)
The loop breaks when it encounters a comma, and Python ignores the rest of the input string.
6. For loop with an else
We can use the else conditional clause with a “for” loop. Python executes the else clause after the entire “for” loop. If the for loop has a break clause, Python executes the else clause only if the break clause is not executed.
As per Python documentation,
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.Python 3.7 documentation
The first example shows the else clause executing
num_list= [1,18,90,36,45,80,17,65,49,22,38,15,10,12] max_num = 99 for num in num_list: if num > max_num: break else: print("Max number is still", max_num) print("\n")
In the second example, we use the same code. We have just adjusted the input such that the break runs.
num_list= [1,18,90,36,45,80,100,17,65,49,22,38,15,10,12] max_num = 99 for num in num_list: if num > max_num: print("New Max number is: ", num) break else: print("Max number is still", max_num) print("\n")
7. Nested Loops
We can nest one for loop inside another. We are allowed to nest as many For loops as we wish, but it is usually not recommended to nest more than two loops inside each other. A classic example of nest loops is prime numbers.
for number in range(2, 20): for num in range(2, number): if number % num == 0: break else: #The else is for the for loop print(number, 'is a prime number')
8. Empty For loop
When we want to keep the for loop empty, we can put the “pass” clause inside. If we leave an empty for loop without any code inside, Python throws an “expected an indented block” error.
for i in range(1,10):
To avoid the above error, the code should be:
for i in range(1,10): pass
In this article, we looked at examples of “for” loops in Python. A for loop is one of the most useful and widely used loops in Python and has many valuable options that we can use to perform a wide variety of tasks.
10. More articles
11. Download the Source Code
That was a tutorial about the For loop in Python.
You can download the full source code of this example here: For Loop in Python
Last updated on Dec. 16th, 2021