Beginner's Guide On For Loop in Python
Beginner's Guide On For Loop in Python
Introduction
This post is for beginners who are trying to learn Python and they will find this step-by-step guide very easy to understand.
Here, I will be first introducing
the concept of the 'for' loop in Python, and thereafter, I will proceed to
explain the significance and methods of using this loop in your Python projects
with several easy-to-understand examples and source code.
What is a 'for' loop
A 'for' loop in
Python is used to loop over a sequence and it is very useful when you perform
tasks in your python functions. The 'for' loop could be used for looping or
iterating over a list, tuple, set, dictionary or a string. We will see the
examples below.
During the phase of looping through a list for example, after creating the variable name to specify each item in the list, we will decide what is the action that is to be executed in the phase of this iteration whereby each and every item specified inside the list is accessed one by one in the exact order that you want it to be performed. We will see more in detail when we go through the examples one by one. The only difference in the case of dictinaries is that through such iteration, is looping through the dictionaries will first provide access with the keys which in turn, will provide access with the individual items as required.
How to Create a for Loop
In order to
create a 'for' loop, we need to create a variable and an object through which
we want to iterate this loop.
Looping through a List
The process of looping through a list involves iterating through all the items contained inside the list and thereafter execute some task on every item in the list, one by one. Therefore, we use a 'for' loop in the case, you wish to carry out some task on each and every item inside the list, in order to get the desired output.
In the following example, we have a list called items with a list of items, namely, "table", "desk" and "sofa" and we want to loop through these items one by one and then print out the items in the list. The code for this example is indicated below. When we write, 'for item in items', we mean for iterating through or going through the items, item by item, or in other words, one by one.
for item in
items:
print(item)
In the second example for looping through a list, we consider a list called my_list with numbers from 1 to 5. Here we wish to loop through all the numbers 1,2,3,4 and 5 in this list and then first multiply each of the numbers by 2, and thereafter, print out the result of this multiplication. So, the first item is number 1 and when multiplied by 2 will yield result of 2, then the next number in the sequence is 2 which when multiplied by 2 will give you 4 as a resultant number, then, the next number 3 when multiplied by 2 will give 6 as a resultant number, then, 4 multiplied by 2 will give you 8 as a resultant number and the last number in the list is 5 which when multiplied by 2 will give you the number 10 as a resultant number in the list.
So, now, after performing the multiplication
by 2 on each of the existing numbers of the list will give you a resultant
items of 2,4,6,8,10 respectively in the list. Hence when you print out the
result of the multiplication as specified in the task in the for loop, you will
get the outcome with the new numbers as mentioned above in the list.
my_list = [1,
2, 3, 4, 5]
for item in my_list:
print(item * 2)
Looping through String
In order to
access each of the character contained in a string, we could use the 'for' loop for the purpose
of iteration. Take a look at the example code sample given below where we consider the
string 'meerateachestech' in which we would like to access all the characters in
this string and it is for this purpose that we create a 'for' loop here by using the variable x to iterate over each of the characters in this string.
After the
iteration, we perform the task of printing out the characters and in the
outcome
In the second
example as shown below, we have another string called my_string, which contains the
string, "Hello" and here we loop through each and every character in
the string by saying for char in my_string,
meaning, for every character in my_string, we will get all
the characters, as shown in the code block below.
for x in
"meerateachestech":
print(x)
#loop through every character in the string and print out the characters one by one.
my_string="Hello"
for char in my_string:
print(char)
Using the for loop with break statement
The break
statement stops the loop before looping through all the items in the list. If
we use the break
statement, we will be stopping the loop right at the point, we use the break statement,
thereby stopping the iteration through all of the items or rather preventing it from looping
through the rest of the items in the list since the iteration had to stop
exactly the list since
the iteration had to stop exactly the time the break statement was declared.
In the below
code, we notice that fruits is the list with three fruits namely 'orange', 'grapes', and 'berry' When we write, for fruit
in fruits, we mean, loop through every fruit in the
fruits and then print out the fruit in
the list, one b one. Then we use a conditional statement
that if a fruit while iteration happens
to be 'grapes', then use the break statement. When the break statement is used, immediately the
iteration of the items in the loop is stopped at the point when the items are reaching
the value of grapes. So looping will stop after fruit reaches a value of
grapes.
In the output,
we will only see 'orange' and 'grapes' because the iteration stops at grapes, it will not
loop further through the rest of the fruits, that is berry and berry will not
be printed out. We
can clearly see that berry comes after grapes.
#Code:
fruits =
["orange","grapes","berry"]
for fruit in fruits:
print(fruit)
if fruit == "grapes":
break
#output orange
grapes
fruits =
["orange","grapes","berry"]
for fruit in fruits:
#print(fruit)
if fruit == "grapes":
break
print(fruit)
#output orange
#reason break
is before print
In the second
case, when the break statement comes before the print statement, the iteration is stopped in
the loop and the code block after the break statement is not able to run with the result that
we do not get orange and berry in the output as the code block stops executing when the break
is called before the print statement right after the first item in the list.
The reason for
this changed behaviour is because the break statement comes before the print statement in
this code block as shown below.
Using the for loop with continue statement
When we use the
for loop with the continue statement, we will observe that we can skip or miss out on a
specific iteration and then move on to the next iteration. So the continue statement is
responsible for stopping the loop at that specific point of using the continue statement and
then jump to the next iteration whereby the code block in the previous block below the
continue statement, will not be carried out and then it stops the current
iteration of loop and
continues with the next iteration.
In the below code, we find that the iteration
stops at berry so it will not print out berry but it will print
out the rest of the fruits. In other words it will skip the fruit 'grapes' as
we used the
continue statement at grapes.
#Code:
fruits =
["orange", "grapes", "berry"]
for fruit in
fruits:
if fruit == "grapes":
continue
print(fruit)
#output orange
berry
Using the for loop with the range function
When looping
through a range function, the range function will help in repetitive action for a specified
number of times. That is, for example, if we want to iterate through a code block, for a
specified number of times, then the range function combined with a for loop is very useful. The range
function returns a output sequence of numbers that starts from 0 by default and keeps
incrementing or increasing by 1 as a default option an thereafter ends at a
specific number that is
mentioned in the range.
The range
function can use parameters to specify a start value and an end value , for example,
range(2,7) means a range of numbers starting from 2 (not the default 0) and ends at 7, but
not inclusive of 7. So, the output will carry numbers, 2,3,4,5,6 since end point is not
inclusive by the rule of a range function.
Using the for loop with a range function having a start parameter
The default start parameter of a range function is 0 but if we use a different value other than the default value of 0, range function will yield an output with a start value that is provided in the parameter as a start value and if no parameter is provided as a start value, then then the output range will start with a default value of 0 as shown in the code block provided.
for x in
range(7):
print(x)
#outcome 0 1 2
3 4 5 6
for x in
range(2,7):
print(x)
#output 2 3 4 5
6
Using the for loop with a range function having the Increment Parameter
The range function defaults to incrementing by 1 but it is possible to include the incrementing value by adding a third parameter in the range function parenthesis as shown below in the code block.
for x in
range(2,30,3):
print(x)
#output 2 5 8 11 14 17 20 23 26 29
Using for loop with else loop
When we use the
else condition for a range function, the for loop states a block of code or rather a task
to be executed once the loop is completed.
Example
Print all
numbers from 0 to 5 , then,print a
message when the loop has completed as
shown in the code
block below. In the output we get numbers from 0 to 6 since the range function has just one
parameter value , that is 7.
So the output
will give resultant numbers from default 0 and go on to print numbers until 6 and then also
print out "done" after finishing the loop and it doesn't print 7
which is the range
function parameter in this case. Because, by default, the resultant end number
will be 1 less than
the provided number here. So , after printing the last number 6, it will print
"done" as shown in the outcome of the code block.
#Code:
for x in
range(7):
print(x)
else:
print("done!")
#output 0 1 2 3
4 5 6 Done
The else loop will not be executed if the if loop is stopped by a break statement , as shown in the code block below.
#Code:
for x in
range(7):
if x == 3:
break
print(x)
else:
print("finally done!")
#output 0 1 2
#if loop breaks
the else
loop is not executed
Using nested for loops
When you need to iterate over multiple collections or carry out tasks that require nested loops or iterations,then you could use the nested "for loops"
sizes =
["big", "small", "medium"]
fruits =
["oranges", "grapes", "berry"]
for size in
sizes:
for fruit in fruits:
print(size, fruit)
#output big
oranges big grapes big berry
small oranges
small grapes small berry
medium oranges medium grapes medium berry
Using the for loop in Iterating through dictionaries
We can loop through the keys, values, or key-value pairs of a dictionary using a for loop as shown in the example below. my_dict is a dictionary with a key-value pairs as shown below whereby a,b,c are the keys and the valued are 1,2 and 3 respectively. Hence in the for loop we need to mention both the key as well as value and we also write dot items() in order to loop through the items in this dictionary. Then inside the print() function we need to write both the parameters, the key and the value.
my_dict =
{"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
print(key, value)
Using the for loop in Iterating through a tuple or set
It is possible to use the for loops to iterate through tuples as well as sets. Let us consider an example of a tuple as shown below. my_tuple contains three numbers, namely, 10, 20 and 30.
We iterate through items in the tuple by saying for item in my_tuple , print each item in the tuple. Ofcourse, this is the English way of putting the execution shown below in the for loop in the code block below. please make a note here that whatever term is used in the for loop iteration it is the same term that needs to be printed out.
Below, had we written items instead of item in the for loop, then we need to type items as the parameter in the print() function.
Hope, it is clear now.
my_tuple = (10,
20, 30)
for item in my_tuple:
print(item)
When to use the for loops
In general, use a for loop when you know how many times the loop should run. If the number of iterations is not known in advance or depends on a condition, a while loop might be more appropriate.
Conclusion
For loops are used when you know how many iterations you want to go through. While loops are used when you don't know the number of iterations you want to go through. loop is typically used when you have a known sequence of items, such as a list, string, or range, and you need to iterate over each element in that sequence.
This is all about the basics for understanding the 'for loop' in Python for beginners. I hope, I have made myself clear and if you still have any questions, please do not hesitate to mention or shout out in the comment section below. 😀
Comments
Post a Comment