In general for loops are for iterating over a collection. The for loop in Python is also referred to as the for…in
loop. This is due to its unique syntax that differs a bit from for loops in other languages. A for loop is used when you have a block of code that you would like to execute repeatedly a given number of times.
The loop contrasts and differs from a while
statement in that in a for
loop, the repeated code block is ran a predetermined number of times, while in a while
statement, the code is ran an arbitrary number of times as long as a condition is satisfied.
Python for loop Syntax
The standard syntax for a for loop is:
for value in collection: # do something with value
Here, value is the variable that takes the value of the item inside the collection on each iteration.
Similarly the elements in the collection or iterator are sequences (tuples or lists, say), they can be conveniently unpacked into variables in the for loop statement:
for a, b, c in iterator: # do something
In python we do not provide an end block unlike other programming languages, here indentation is used to understand the end of for loop
. So make sure the next line after for loop begins with some whitespace (count of whitespace doesn't matter) and thereafter until the for loop is used, you must use the same or higher indentation value.
List of Python Data Types which are iterable
I hope you are familiar with different Python Data Types such as List, Dictionary, Tuple etc. So let's check which all data types can be used in a loop to iterate over individual elements and which all data types are not iterable.
We will use iter
which is a built-in function used to obtain an iterator from an iterable. I have added different data types in this script and then using iter
module to check if a loop can be used to iterate over individual elements of the respective data types.
Output from this script:
~]# python3 for-loop-1.py
<list_iterator object at 0x7f112d8d0278>
<str_iterator object at 0x7f112d8d0278>
<tuple_iterator object at 0x7f112d8d0278>
<dict_keyiterator object at 0x7f113c38ef98>
<set_iterator object at 0x7f113c30da20>
So all these data types are iterable, but there are some more data types such as float
, int
which are not iterable.
Traceback (most recent call last):
File "for-loop-1.py", line 13, in <module>
print(iter(myint))
TypeError: 'int' object is not iterable
Below tables contains a bunch of different data types available in Python and if you can use a loop to iterate over them:
Data Type | Example | Iterable? |
---|---|---|
String | mystr = "Deepak" |
Yes |
Tuple | mytuple = ('one', 'two', 'three') |
Yes |
List | mylist = [1,2,3] |
Yes |
Dictionary | mydict = {'key1': 'val1', 'key2': 'val2'} |
Yes |
Set | myset = {"apple", "banana", "cherry"} |
Yes |
Integer | myint = 45 |
No |
Float | myfloat = 45.5 |
No |
Complex | mycomplex = 45ab |
No |
Example-1: Python for loop with a list
In this example we will use for loop to iterate over the individual values of list. We declare a variable called numbers and initialize numbers to a list of integers from 1 to 5. next loop through this list and inside the loop calculate the square of num
by multiplying it by itself.
Output from this script:
~]# python3 for-loop-2.py
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
Example-2: Python for loop with string
In this example we will use a string with for
loop. Now in our previous example we used a "list" with some values where for loop was used to iterate over individual values of the list. But with string for loop will iterate over individual character.
We will create a python script which will take user input for a string, then with a for loop we will iterate over the character of the input string. Next we will add an index value along with each character such that the output looks like
p --> 0
y --> 1
t --> 2
h --> 3
o --> 4
n --> 5
Following is our python script;
Output from this script:
~]# python3 for-loop-3.py
Enter your string: python
p --> 0
y --> 1
t --> 2
h --> 3
o --> 4
n --> 5
Example-3: Python for loop with dictionary
Now there are different methods to use for loop with a dictionary. In this single script I have covered different scenarios and methods to print key, value or key:value pair combined using for loop from a python dictionary:
Output from this script:
~]# python3 for-loop-4.py
----- Scenario-1-----
KEY: a
KEY: b
KEY: c
----- Scenario-2-----
KEY: a
KEY: b
KEY: c
----- Scenario-3-----
VALUE: 1
VALUE: 2
VALUE: 3
----- Scenario-4-----
KEY:VALUE: ('a', 1)
KEY:VALUE: ('b', 2)
KEY:VALUE: ('c', 3)
----- Scenario-5-----
KEY: a
VALUE: 1
KEY-VALUE: a : 1
KEY: b
VALUE: 2
KEY-VALUE: b : 2
KEY: c
VALUE: 3
KEY-VALUE: c : 3
So for all the scenarios we have key, value or combined key-value pair in the output.
Example-4: Python for loop with else
statement
As with a while
statement, an else statement can also be optionally used with a for loop. Here is an example where we have a list with some integers. We will use a for loop to iterate through this list and check if certain numbers are part of this list.
The syntax to use for..else
block would be:
for item in sequence: process(item) else: # no break suite
for..else
block can be confusing at times because the else block will get executed always
. Normally we know the else block is executed only when the first block condition fails but here with for..else
block it is different. Hence I have mentioned as no break
because if break is not specified in the for
block, the else
block would be executed anyhow.
Let us take some examples:
Here in my sample python script I have a list and using for loop I will check each value of this list. Now I have added one success and one failure if condition to verify our for-else:
block
#!/usr/bin/env python3 mylist = [1,2,3,4,5] for val in mylist: if val == 10: print('Found 10 in mylist') if val == 5: print('Found 5 in mylist') else: raise ValueError("10 not found in mylist")
Output from this script:
~]# python3 for-loop-5.py Found 5 in mylist Traceback (most recent call last): File "for-loop-5.py", line 11, in raise ValueError("10 not found in mylist") ValueError: 10 not found in mylist
Now the script has executed properly but this is not correct as fortunately one of the if conditions inside the for loop failed and ValueError
was raised but what if both the if condition were success, let's check that out:
#!/usr/bin/env python3 mylist = [1,2,3,4,5] for val in mylist: if val == 1: print('Found 1 in mylist') if val == 5: print('Found 5 in mylist') else: raise ValueError("1 or 5 not found in mylist")
Output from this script:
~]# python3 for-loop-5.py Found 1 in mylist Found 5 in mylist Traceback (most recent call last): File "for-loop-5.py", line 11, in raise ValueError("1 or 5 not found in mylist") ValueError: 1 or 5 not found in mylist
As you see, even though 1 and 5 are part of the list, the else block was executed which raised ValueError
. So in such case it is important that we always use a break
statement in the success condition so that the loop doesn't execute else block:
Now I have removed additional if condition as it doesn't make much sense or we can add break at two places. I have added break
statement in the if condition so that if the condition matches we exit the for loop.
#!/usr/bin/env python3 mylist = [1,2,3,4,5] for val in mylist: if val == 1: print('Found 1 in mylist') break else: raise ValueError("1 or 5 not found in mylist")
Output from this script:
~]# python3 for-loop-5.py
Found 1 in mylist
So the else block is not executed this time.
Example-5: Python for loop with range()
function
Python's range function is a built-in function that generates a list of numbers. This list is mostly used to iterate over using a for loop.
This function is used when you want to perform an action a predetermined number of times, where you may or may not care about the index, for instance, finding or calculating all even numbers between 0 and 100, where Python will list or print out all even numbers in that range, excluding 100, even though it is an even number. You can also Python for loop with range to iterate over a list (or another iterable) while keeping track of the index.
The basic syntax of the range
function is as follows:
range([start], stop, [step])
Here is a breakdown of what each parameter does:
- start: This is the starting number of the sequence.
- stop: This means generate numbers up to but not including this number.
- step: This is the difference between each number in the sequence.
A simple script to understand how range works:
#!/usr/bin/env python3 for val in range(5): print(val)
The output from this script:
~]# python3 for-loop-6.py
0
1
2
3
4
The range(5)
class basically tells the function to generate numbers from 0 to 5, but not including 5. The range function starts at zero if a start point is not defined as with this form of the function call.
Next we will use range to define start and stop:
#!/usr/bin/env python3 for val in range(10, 15): print(val)
Output from the script contains the range from 10 till 14 as we have defined start as 10 and stop as 15.
~]# python3 for-loop-6.py
10
11
12
13
14
How is the step parameter used? The step parameter defines the difference between each number in the generated list. If you set step to 5, the difference between each number on the list will be a constant of 5. This can be useful when you want to generate a very particular set of numbers between any given two points.
In this example we give a range from 10 to 20 and the numbers would step by 3:
#!/usr/bin/env python3 for val in range(10, 20, 3): print(val)
Output from this script:
~]# python3 for-loop-6.py
10
13
16
19
You can also reverse the step up by using a negative value, for example I want to pint all values between 20 and 10 with a difference of 2:
#!/usr/bin/env python3 for val in range(20, 10, -2): print(val)
Output from this script:
~]# python3 for-loop-6.py
20
18
16
14
12
Here as you observed, the loop was iterated backwards because we gave negative step up value of -2
In this example I have defined a list, next we will run a for loop for individual values of the list by getting the length of the list.
Output from this script:
~]# python3 for-loop-6.py
The length of mylist: 6
1
5
6
2
7
9
Example-6: Nested for loop in Python
Nesting can be defined as the practice of placing loops inside other loops. Although it is frowned upon in some applications, sometimes, it is necessary to nest loops to achieve the desired effect.
One of the use cases for nesting loops is when you need to access data inside a complex data structure. It could also be as a result of a comparison of two data structures. For instance, a computation that requires values in two lists would have you loop through both lists and execute the result.
In our next example script we will create a variable called groups
, which is a list that contains three other lists of three integers each. If we loop over the first list then we will get [1,2,3]
but to get individual integer we must add another loop to iterate over this list.
#!/usr/bin/env python3 groups = [[1, 2, 3], [4, 5, 6]] for group in groups: for num in group: square = num * num print(num,' squared is ', num)
Output from this script:
~]# python3 for-loop-7.py
1 squared is 1
2 squared is 2
3 squared is 3
4 squared is 4
5 squared is 5
6 squared is 6
As you can see, we are able to loop over the individual groups of integers and perform calculations on the individual integers by nesting the for loops.
Example-7: Use break
statement with Python for loop
We have already had one example where we used break
statement with for..else
block to come out of the loop. The break
statement allows you to exit a loop based on an external trigger. This means that you can exit the loop based on a condition external to the loop. This statement is usually used in conjunction with a conditional if
statement.
Here is a simple example to demonstrate break
statement:
#!/usr/bin/env python3 for num in range(1,6): print(num) if num == 4: break print('Outside for loop')
Our for loop will iterate over the range from 1 to 6. If 4 is found in the range then come out of the loop. Output from the script:
~]# python3 for-loop-8.py
1
2
3
4
Outside for loop
If you notice, as soon as num
was equal to 4 the loop exits but the script continue to execute for functions outside the for loop. So you should not get confuse break
with exit
statement.
Example-8: Use continue
statement with Python for loop
The continue statement allows you to skip over the part of a loop where an external condition is triggered, but then goes on to complete the rest of the loop. This means that the current run of the loop
will be interrupted, but the program will return to the top of the loop and continue execution from there.
As with the break statement, the continue statement is usually used in conjunction with a conditional if statement.
#!/usr/bin/env python3 for num in range(1, 5): if num == 2: continue print(num) print('Outside for loop')
In this example we have added an if condition inside for loop. So if num
is equal to 2 then we use continue which means "do nothing" and skip the current iteration. Let's check the output of this script:
~]# python3 for-loop-9.py
1
3
4
As expected we don't have an output for 2 because the iteration was skipped when num
was equal to 2.
Example-9: Use pass
statement with Python for loop
The pass statement allows you to handle an external trigger condition without affecting the execution of the loop. This is to say that the loop will continue to execute as normal unless it hits a break
or continue
statement somewhere later in the code.
As with the other statements, the pass statement is usually used in conjunction with a conditional if statement.
Let us understand pass
statement with an example. Normally when we add an if condition, we always add some tasks for a condition match but if you have a requirement to match a condition and do nothing i.e. continue with remaining part of the code then we use "pass
"
#!/usr/bin/env python3 for num in range(1, 5): if num == 2: pass else: print(num) print('Outside for loop')
Now I have modified my previous code and added an if..else
block. Normally if I just put
for num in range(1, 5): if num == 2: # No tasks here else: print(num)
then the script will fail because no task is assigned for if condition, so we add "pass
"
Output from our script:
~]# python3 for-loop-9.py
1
3
4
Outside for loop
So similar to continue statement, the print statement for num == 2
was skipped.
Example-10: Use Python for loop to list all files and directories
In this example we will create a python script which will prompt for user input. The end user must provide a path which will be used by the script to print all the files and directories.
Output from this script:
~]# python3 for-loop-10.py
Enter your directory path: /tmp/dir1
all files and directories: ['file1', 'sub-dir2', 'sub-dir1', 'file2']
/tmp/dir1/file1 is a file
/tmp/dir1/sub-dir2 is a directory
/tmp/dir1/sub-dir1 is a directory
/tmp/dir1/file2 is a file
We use os
and sys
module in this script to check for files and directories inside the system.
Conclusion
In this tutorial, we have increased our knowledge of looping structures. We have seen the structure of a for loop
and looked at practical examples. We have also looked into the range
function and how it comes in handy when you need to quickly iterate over a list.
Apart from that, we have also covered how and when to nest loops
and how to break
out of loops prematurely under different conditions and with differing results by using the break
, continue
, and pass
statements.
Further Readings
Python3 for loop statement
Python for loop range
Python for loop with break and continue statement