Statements are typically executed in order: the first statement in a function is executed first, then the second, and so on.
You may find yourself in a position where you need to run a block of code multiple times.
Different control structures are available in programming languages, allowing for more sophisticated execution routes.
To meet looping requirements, the Python programming language supports the following types of loops.
The loops can be executed in three different ways in Python.
While all of the methods provide comparable basic functionality, they differ in syntax and the time it takes to check for conditions.
In this page we will discuss about Python For Loop in brief.
Iterating over a sequence is done with a for loop (that is either a list, a tuple, a dictionary, a set, or a string).
This is more like an iterator method seen in other object-oriented programming languages than the for keyword in other programming languages.
The for loop allows us to run a sequence of statements once for each item in a list, tuple, set, or other data structure.
for iterator_var in sequence: statements(s)
On each iteration, iterator_var is the variable that takes the value of the item inside the sequence.
The loop will continue until the last item in the sequence is reached.
Indentation is used to separate the body of the for loop from the remainder of the code.
It can be used to iterate across a set of iterators and a range of values.
animal = ["cat", "dog", "cow"] for var in animal: print(var)
cat dog cow
There is no need to set an indexing variable before using the for loop.
Control statements in loops alter the execution sequence.
All automatic objects generated in a scope are deleted when execution exits that scope.
The following control statements are supported by Python :
🚀 Break
🚀 Continue
🚀 Pass
If you've ever done any programming, you've almost certainly encountered a for loop or something similar.
Many programming languages provide conditions in their for loop syntax, such as a relational expression to decide whether the loop is complete and an increment expression to determine the next loop value.
Instead, in Python, this is done by producing the proper sequence.
A for loop can be used with any object that has an iterable method.
Even strings, despite the lack of an iterable function - but more on that later.
An iterable technique simply means that the data can be displayed in a list format, with many values arranged in a logical sequence.
By constructing an object using the next() and iter() methods, you can define your own iterables.
This implies that when it comes to for loops in Python, you'll rarely be working with raw numbers, which is wonderful for just about everybody!
We can break the loop before it loops over all of the objects by using the break statement:
Keyword :
break;
animal = ["cat", "dog", "cow"] for var in animal: if var=="dog" : break print(var)
cat
The print statement will not be executed in the given example since the loop is broken by the break statement.
We can use the continue statement to end the current loop iteration and begin the next.
Keyword :
continue
animal = ["cat", "dog", "cow"] for var in animal: if var=="dog" : continue print(var)
cat cow
The continue statement's purpose is to skip the current iteration of a loop and move on to the next one.
For loops cannot be empty, however if you have an empty for loop for some reason, use the pass statement to prevent an error.
Keyword :
pass
for x in [0, 1, 2]:
pass
The range() function can be used to create a numeric sequence.
range(10) generates a range of values from 0 to 9. (10 numbers).
Range(start, stop, step size) can also be used to define the start, stop, and step size.
If step size is not specified, it defaults to 1.
In some ways, the range object is "lazy" because it does not generate all of the numbers that it "contains" when we create it.
It isn't an iterator, though, because it supports in, len, and __getitem__ actions.
Because it would be inefficient to save all of the values in memory, this function does not do so.
As a result, it remembers the start, stop, and step size, as well as generating the next number on the fly.
We can use the function list to force this function to output all of the elements ().
range(start, stop, step size)
🚀 The start indicates the start of the iteration.
🚀 The stop indicates that the loop will continue until it reaches stop-1.
Iterations 1 to 4 will be generated by range(1,5).
It's a choice.
🚀 The step size is used to skip the iteration's specific numbers.
It's entirely up to you whether or not you want to use it.
The step size is set at 1 by default.
It's a choice.
print(range(15)) print(list(range(15))) print(list(range(2, 8))) print(list(range(2, 15, 2)))
range(0, 15) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] [2, 3, 4, 5, 6, 7] [2, 4, 6, 8, 10, 12, 14]
n = 10 for i in range(1,11): x = n*i print(n,"*",i,"="x)
10*1=10 10*2=20 10*3=30 10*4=40 10*5=50 10*6=60 10*7=70 10*8=80 10*9=90 10*10=100
With a sequence of numbers, we may utilise the range() method.
The len() and range() functions are used to cycle across a sequence using indexing.
Let's understand this by taking an example,
list = ['Apple','Banana','Grapes','Pineapple'] for i in range(len(list)): print(list[i])
Apple Banana Grapes Pineapple
Unlike other programming languages such as C, C++, or Java, Python allows us to utilise the else statement with the for loop, which is only performed when all iterations have been completed.
It's worth noting that the else statement will not be executed if the loop contains any break statements.
Python allows you to associate an else statement with a loop expression.
When the else statement is used with a for loop, it is performed after the loop has finished iterating the list.
The following example shows how to use an otherwise statement in conjunction with a for statement to find print "even" if numbers is even or "odd" if number is odd between 10 and 20.
for i in range(10,20): if num%i == 0: print("even"); else: print("odd");
even odd even odd even odd even odd even odd
A nested loop is one that is contained within another loop.
For each iteration of the "outer loop," the "inner loop" will be run once.
You use a "nested loop" when you have a block of code that you want to run x number of times and then another block of code within that code that you want to execute y number of times.
These are frequently used in Python when dealing with a list of lists - an iterable object within an iterable object.
n = 5 for i in range(0,n+1): for j in range(i): print(*,end = '') print()
* * * * * * * * * * * * * * *
AThe enumerate() method is used to iterate over the indices in a sequence.
The counter is added to iterable by the enumerate() function, which starts at 0 by default.
color = ['red', 'pink', 'blue', 'green']
for index, value in enumerate(color):
print(index, value)
0 red 1 pink 2 blue 3 green
We can iterate over numerous lists at the same time. The zip() function, which is integrated into the Python loop, is used for this.
from array import * arr = arry(i, [10, 20, 30, 40, 50, 60]) for x in arr : print(x)
10 20 30 40 50 60
Another method of iterating through each item is to use an index offset into the sequence. Here's a simple illustration:
fruits = ['apple', 'banana', 'mango', 'cheery'] for i in range(len(fruits)): print 'Fruit :', fruits[i] print "Completed!"
Fruit : apple Fruit : banana Fruit : mango Fruit : cheery Completed !
The len() built-in function, which returns the total number of elements in the tuple, and the range() built-in function, which returns the actual sequence to iterate over, came in handy here.
Let's see some problems that solved using for loop
str = "LearnPython"
for i in str:
print(i)
L e a r n P y t h o n
list = [1,2,3,4,5,6,7,8,9,10]
n = 2
for i in list:
num = n*i
print(num)
2 4 6 8 10 12 14 16 18 20
list = [1,2,3,4,5,6,7,8,9,10]
sum = 0
for i in list:
sum = sum + i
print(sum)
55
for i n range(10):
print(i,end = ' ')
1 2 3 4 5 6 7 8 9
for i in range(1,10,2):
print(i)
1 3 5 7 9
The len() built-in function, which returns the total number of elements in the tuple, and the range() built-in function, which returns the actual sequence to iterate over, came in handy here.
Crack your next tech interview with confidence!
In this article, we looked at Python for loop and the many statements that it has. We also showed how to use the break, continue, and pass statements in a Python for loop with a visual example.