- Python Basics
- Python Home
- Python History
- Python Applications
- Python Features
- Python Versions
- Python Environment Setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control & Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break Vs continue
- Python pass Vs continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List Vs Tuple Vs Dict Vs Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date & Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes & Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class Vs Static Method
- Python @property Decorator
- Python Regular Expressions
- Python Send E-mail
- Python Event Handling
- Python Keywords
- Python All Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
- Python Test
- Python Online Test
- Give Online Test
- All Test List
for Loop in Python
The for loop in Python, is used to execute some block of code, multiple times. This article is created to provide all versions of for loop in Python. That is, this article deals with:
- Iterating string using for loop
- Iterating list using for loop
- Iterating for loop using range() function
- for loop with range(), started by specified value
- for loop with range(), started and incremented by specified values
- Iterating for loop in reverse or backward using range()
- for loop with else statement
- break statement in for loop
- continue statement in for loop
- pass statement in for loop
- nested for loop
Let's first see the syntax of for loop. And then under the Python for Loop Example section, one by one, all the above versions of for loop gets described with example programs.
Python for Loop Syntax
The syntax to use for loop in Python is:
for loop_variable in sequence: statement_1 statement_2 statement_3 . . . statement_n
Or,
for loop_variable in sequence: body of the loop
Python for Loop Example
This section is created to describe all the versions of for loop with the help of example programs, one by one.
Iterating String Using for Loop
The for loop can be used to iterate all characters of a string, one by one, like shown in the program given below:
string = "codescracker" for c in string: print(c)
The output produced by above program is shown in the snapshot given below:
The above program can also be written as:
for c in "codescracker": print(c)
The dry run of above program, goes like:
- At first iteration, the first character of string "codescracker", that is 'c' gets initialized to the loop variable, that is c
- So using the print() function, the value of c, that is 'c' gets printed
- At second iteration, the second character of string "codescracker", that is 'o' gets initialized to the loop variable, that is c
- Again using the print(), the new value of c, that is 'o', gets printed
- This process continues, until the last character of string "codescracker", that is 'r'
- In this way, all the characters of string gets printed one by one as shown in the snapshot given above
That is, whatever you provide after:
for c in
gets treated as a sequence. Since in above program, there is a string "codescracker". Therefore, the string gets treated as a sequence, which is the sequence of characters. For example, if the above program gets modified with the program given below:
for c in "codescracker", 2, True, 'c', 3.4: print(c)
Then, this time:
"codescracker", 2, True, 'c', 3.4
gets treated as sequence. Therefore, one by one, all the five elements gets printed one by one like shown in the snapshot given below:
Note - Anything can be used as sequence in for loop, that are iterable in Python.
Since the int object is not iterable. Therefore the following program:
for c in 1234: print(c)
produces error like shown in the snapshot given below:
Iterating List Using for Loop
The list can also be iterated using for loop as shown in the program given below:
mylist = [1, 2, 3, 4, 5] for i in mylist: print(i)
The output produced by above program is:
The above program can also be written as:
for i in [1, 2, 3, 4, 5]: print(i)
Or
for i in 1, 2, 3, 4, 5: print(i)
The dry run of above program, goes in similar way as described the dry run of previous program. That is, all the five elements gets initialized to i (the loop variable of above program) one by one. And the value of i gets printed as shown in the output given above.
Here is another program, uses for loop to iterate list:
mylist = ['P', 'Y', 'T', 'H', 'O', 'N'] for i in mylist: print(i)
Now the output produced by above program is:
P Y T H O N
And here is another program, uses for loop to iterate list of words:
mylist = ['python', 'on', 'codes', 'cracker'] for i in mylist: print(i)
The snapshot given below shows the output produced by above program:
This time, the list contains four words and the list gets iterated by elements, without caring whatever the element is, that is, whether it is a number, character, or words etc. The elements gets iterated one by one.
Iterating for Loop Using range() Function
As far as I've seen while programming in Python since last 5-6 years. Most of the time, for loop comes with range() function. That is, most of the time, we need range() in for loop. Here is a simplest Python code of for loop with range().
for i in range(10): print(i)
The snapshot given below shows the sample output produced by above program that uses range() function in for loop in Python:
In above program, the range(10) generates a number starting with 0, increments by 1, and stops at 9 (one less than the value 10). That is, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 are the 10 numbers gets generated by range(). And all the numbers gets printed one by one, in same way as done in previous programs.
for Loop With range(), Started By Specified Value
If you provide two parameters to range(). Then the iteration starts with the value of the first parameter. Let's create another version of the program that uses for loop with range(). This time, I've provided two parameters to range():
for val in range(10, 20): print(val)
Now the output produced by above program is:
Note - All the details about range() Function in Python, is provided in separate tutorial.
for Loop With range(), Started And Incremented By Specified Values
To increment the value of loop variable by a specified value, we need to provide three parameters to range(). Because, if you provide two parameters, then the first parameters indicates where the iteration starts, the second parameter indicates, where the iteration stops. But providing the third parameter, indicates to increment the loop variable by the value of third parameter. Let's take a look at the program given below:
for val in range(2, 22, 2): print(val)
The loop iteration starts with 2, and continues by incrementing 2 each time, stops at 20 or 2 less before 22 (the second parameter), as shown in the output given below:
Iterating for Loop In Reverse Or Backward Using range()
To iterate for loop in backward or in reverse, we need to provide 3 parameters to range() function. The first parameter is the value, where the iteration starts with. The second parameter is the value, where the iteration stops. And the third parameter's value must be in minus form to decrement the loop variable at each iteration. If -1 is provided, then the loop variable gets decremented by 1 each time.
for val in range(10, 0, -1): print(val)
That is, the first parameter 10 refers to the number where the iteration starts, the second parameter 0 refers to the end, but not with 0, the iteration stops one before the number, that is 1, and finally the third parameter is provided with minus 1 (-1), so that to iterate in reverse.
The output produced by above program is shown in the snapshot given below:
Note - The third parameter, is used to increment/decrement the loop variable. If third parameter value is in positive form, then the loop variable gets incremented by the value. Otherwise if minus form given to third parameter's value, then the loop variable's value gets decremented by that value each time.
Here is another program, prints value in reverse, decremented by 2 each time:
for val in range(10, 0, -2): print(val)
The output produced by above program, is:
10 8 6 4 2
for Loop With else Statement
The else used with for loop, used to execute the statement when the execution of the for loop ends:
for i in range(5): print(i) else: print("Loop Execution finished!")
The output produced by above program is:
break Statement In for Loop
The break statement or keyword inside for loop, generally used to exit from the loop without executing the complete or remaining iteration of the loop
mylist = [1, 2, 3, 4, 5, 6, 7, 8] for i in mylist: if i==6: break print(i)
From above program, the following block of code:
if i==6: break
is used to exit from the loop, when the value of i becomes equal to 6. The output produced by above program will be:
1 2 3 4 5
continue Statement In for Loop
The continue statement inside for loop, generally used to force the program flow to start with new iteration, without executing the remaining statement(s) after the continue keyword/statement, inside the same loop.
mylist = [1, 2, 3, 4, 5, 6, 7, 8] for i in mylist: if i==6: continue print(i)
From the above program, when the condition i==6 evaluates to be True, program flow goes inside the if block. And the continue keyword gets executed. That forces the program flow to continue with new iteration without executing the statement after the continue keyword, in same loop. That is, the statement:
print(i)
does not gets executed when the value of i is 6. The output produced by above program is shown in the snapshot given below:
See, 6 is not available on the output screen.
pass Statement In for Loop
The pass does nothing. Therefore it is used where the syntax of the program needs statement(s), but we does not need to put or execute any statement. Let's take a look at the program given below, that uses pass statement inside the for loop in Python:
print("Before \"for\" loop.") for i in range(5): pass print("After \"for\" loop.")
The output should be:
Before "for" loop. After "for" loop.
Here is another program uses pass inside the for loop in Python:
print("Before \"for\" loop.") for i in range(10): if i==5 or i==6: pass else: print(i) print("After \"for\" loop.")
This time, the output should be:
That is, when the value of i becomes equal to 5 or 6, then the condition evaluates to be True, and the program flow goes inside the if block of for. There the pass just passes the program flow for the next iteration without doing any thing.
Nested for Loop in Python
A loop in Python can also be nested inside another. For example, the program given below nested a for loop inside another:
for i in range(5): for j in range(i+1): print("*", end=" ") print()
The output produced by above program on nested for loop is:
Here is the brief dry run of above program:
- At first iteration, 0 gets initialized to i. Since 0 is less than 5, therefore program flow goes inside the loop with i=0
- Inside the loop, there is another for loop
- Therefore, at first iteration of inner for loop, 0 gets initialized to j. Since 0 is less than i+1 or 0+1 or 1, therefore program flow goes inside the inner loop
- Inside the second loop, a star (*) with a space gets printed on output
- The end is used to change the default behavior of print(). That is, instead of inserting new line after each print(). The end in above program, forces the print() to insert a space
- Now the value of j gets incremented by 1. So j=1. But the value of j, that is 1 is not less than i+1 or 1. Therefore program flow does not goes inside this loop
- So the print() after second for loop gets executed. That inserts a newline on the output screen
- Now the value of i gets incremented. So i=1. And again the value of i, that is 1 is less than 5, therefore program flow again goes inside the loop
- Inside the loop, since there is another for loop. So the execution of that second for loop again begins. With i=1 this time. That is, initially j=0, which is less than i+1 or 1+1 or 2, therefore program flow goes inside the second for loop. So a * with a space gets printed
- Now j=1 which is again less than i+1 or 2. Therefore another * with a space gets printed.
- But at the third iteration, j=2 is not less than 2. Therefore for now, the execution stops
- And the print() gets executed, that inserts a newline
- Now the value of i again gets incremented by 1. That is, i=2 now. Since 2 is again less than 5, therefore program flow again goes inside the loop
- This process continues, until the condition evaluates to be False
More Examples on for Loop
- Find Factorial of a Number
- Print Prime Numbers
- Pattern Programs
- Print Floyd's Triangle
- Add Two Matrices
« Previous Tutorial Next Tutorial »
Follow/Like Us on Facebook
Subscribe Us on YouTube