×

Loops in Python

A loop is a sequence of instructions that is continually repeated until a certain condition is reached.

Typically a certain process is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number.

Table of Contents

for loops

In Python, for loops are used when we know in advance how many times a sequence of statements has to be repeated. They are mostly used when we iterate over a sequence of elements.

for loops are based on the concept of iteration. Each repetition of a process is called iteration and this iteration is used in For loops to run a process of repeating a sequence of instructions.

These for loops make writing a program easy. When there is a need for writing the same statement numerous times with variable values in it, definitely it cannot be hardcoded. If we write all those lines it might take some hundreds of lines just to read the code.

print(1)
print(2)
print(3)
print(4)
---
---
---
print(99)
print(100)

But by using for loops we can just complete the process in two lines by sending the sequence and print the items of the sequence each time we run the loop.

for i in range(1, 101):
     print(i)

The for loop checks the condition of whether there are elements in the iterable( sequence ) that haven’t been iterated yet.

If it’s True i.e., there are still iterations to be performed then the sequence of statements inside the for loop are executed by considering one item per iteration.

The iterations will be executed as long as the condition is True, ie., there are still elements in the iterable to be iterated. When there are no elements left in the iterable to get iterated the condition returns false and the control exits the loop.

Elif 1

The basic syntax of for loop consists of the following:-

  • for keyword
  • variable
  • in keyword
  • iterable or sequence
  • indent at the end
  • Body of the for loop
# header of the for loop
for variable in (iterable or sequence):
     # body of the loop
Elif 5

The for loop is declared by using the keyword for and then followed by a variable. The name of the variable can be anything (such as i, j, etc.,) and is completely chosen by the user.

Elif 4

The variable holds the value of the iterable and that value is automatically updated by the for loop before each iteration starts.

Elif 3

The iterable( sequence ) can be a list, tuple, dictionary, set, or range, etc., Each time the loop runs one item is selected and assigned to the variable of the for loop.

In the end, we declare an indent. All the statements that we write under the indent belong to for loop and statements that we write outside the indent do not belong to the body of the loop.

Here is a sample code using for loop to iterate over a string.

for i in "python":
    print(i)

# Output
p
y
t
h
o
n

Nested for loops

Nesting of the for loops is done when for each iteration of the loop we need to repeat an action a particular number of times.

The condition of the outer for loop checks whether there are items to be iterated or not, once it is evaluated to True then the control is passed to the body of the outer for loop.

At some point the nested for loop is encountered, so once all the iterations of the nested loop are completed then the outer loop is iterated with the next item. The process keeps continuing till all iterables of the outer loop are iterated.

App Seqdeployement 1 1

The below example shows the behavior of the nested loop. For each iterable of the outer loop, the nested loop is completely iterated with all its items.

for i in range(2):
    print("Outer loop")
    for j in range(0, 2):
        print("Inner loop", end = " ")
    print("\n")

# Output
Outer loop
Inner loop 
Inner loop

Outer loop
Inner loop 
Inner loop

Scope of variables in Nested loops

  • Outer loop variable can be used in body of the outer loop
  • Outer loop variable can be used in body of nested loops also
  • It can even be used to create iterable in nested loop
for i in range(2):
    for j in range(1, i+2):
        print(i, j)
# Output
0 1
1 1
1 2
  • The variable of the nested loop can be used only within the nested loop itself
  • If the variable of nested loop is used outside of its scope then error is thrown
for i in range(2):
    print(j)
    for j in range(1, i+2):
        print(i, j)
# Output
NameError: name 'j' is not defined

We can print some interesting patterns using the nested for loops concept.

rows = 5
for i in range(1, rows+1):
    for j in range(rows - i):
        print(" ", end = " ")
    for j in range(i):
        print("*", end = " ")
    print("\n")

# Output
    * 

   * * 

  * * * 

 * * * * 

* * * * *

Nested Loops are great if the algorithm requires them, but you should be aware that the use of nested loops and deeply nested loops can have an impact on the performance of the program because the number of iterations can grow very fast.

In the below example, we can check the number of iterations that have been performed in the nested loops.

The outer loop completes 3 iterations. for each iteration, the nested loop completed 6 iterations. In total 18 iterations.

num_times = 0
for i in range(3):
    for j in range(6):
        num_times +=1
print(num_times)

# Output
18

If the outer loop runs x times and the nested loop runs y times, there will be a total of x*y iterations of the nested loops.

This grows very fast, so if there is an alternative to solving the problems with Nested Loops, that should be the first choice.

For loop using range()

In the place of iterable, we can use the range(). The range is an in-built function that takes integers as parameters and returns a sequence of integers which can be iterated using for loop.

range() with stop as parameter

When we enter a single parameter consider ‘n’, it returns integers starting from 0 to n-1 and these can be iterated using for loop.

# Syntax
for <variable> in range(stop):

This single parameter that we have passed is also known as the stop value, which tells the range function to return integers from 0 to n-1, by incrementing each value by 1. By default, the range returns the values from ‘0’.

Elif 6

These values of the range can be then passed into loop variables to print each element one by one.

for i in range(4):
    print(i)

# Output
0
1
2
3

range() with start and stop as parameters

When we pass two values into range function i.e., they are known as start & stop. range() returns the integers that are in the range of [start, stop-1], each value incremented by 1.

# Syntax
for <variable> in range(start, stop):
If Else 1
for i in range(2, 5):
    print(i)

# Output
2
3
4

range() with start, stop and step

When we pass three values into range function i.e., they are known as a start, stop & step. range() returns the integers that are in the range of [start, stop-1], each value incremented by step.

# Syntax
for <variable> in range(start, stop, step):
Elif 7
for i in range(2, 10, 2):
    print(i)

# Output
2
4
6
8

keypoints about range():-

  • If range is called with one parameter, then the paramter corresponds to stop and the default values of start and step are 0 and 1 respectively
  • If range is called with two parameters, then the paramters corresponds to start and stop( in the same order ) and the default value of step is 1
  • If range is called with three parameters, then the paramters corresponds to start, stop and step( in the same order ) respectively, all values being customized

range() with negative parameters

When we pass single negative parameters which are considered a stop value, it does not return anything and the for loop does not work, since the start and step values by default are 0 and +1 respectively

Since obviously the range function cannot parse backward thus return an empty sequence

for i in range(-4):
    print(i)
print("end of for loop")

# Output
end of for loop
  • But when we pass start and stop into the range function either one or both being negative there is a condition which is start < stop
  • By defualt here the step is +1, so the start value is incremented by +1 and returned till it reached stop
Elif 8
for i in range(-4, -1):
    print(i)

# Output
-4
-3
-2


for i in range(-4, -10):
    print(i)
print("end of for loop")

# Output
end of for loop
  • We can also customize the range with negative parameters, provided the range can only be mutable if step returns values within the range of start and stop
  • start + step in range of [start, stop]
Elif 9
for i in range(7, -3, -2):
    print(i)

# Output
7
5
3
1
-1

Equality among range() objects

We can test the equality among range objects using the comparison operators == and !=. Range objects are considered equal if they return the same sequence.

range(3) == range(3)       -> True
range(2, 7) == range(2, 7) -> True
range(2, 6) == range(2, 7) -> False

Since only the sequence of values is compared and two different combinations of parameters can generate the same sequence, two different calls to range can compare equally.

# Both return same sequence
range(0, 8, 2) == range(0, 7, 2)    -> True

list(range(0, 8, 2))   -> [0, 2, 4, 6]
list(range(0, 7, 2))   -> [0, 2, 4, 6]

for loops iterating over iterables

When we consider iteration over iterable we need to run the body of the for loop once for every element in the iterable. This process remains the same for all the iterable such as strings, list, tuple, dictionary, sets, etc.,

Iterating over a list using for loop

When we pass a list as an iterable into for loop, the body of the for loop is executed for each element of the list. This iteration could return in adding or removing the elements from the list or perform any operations using the elements.

for i in [1, 2, 3]:
    print(i)

# Output
1
2
3

While handling mutable sequences, if we try to update them for example a list, while iterating over it by adding or removing elements, the results that we obtain could be different.

The below example has a list being mutated in each iteration, so the elements are not being removed as we expected.

a = [1, 2, 3, 4, 5, 6]
for i in a:
    print(i)
    a.remove(i)

# Output
1
3
5

This occurs because calling .remove() mutates (changes) the original list in memory and the internal “tracker” used to iterate over the list in the loop is changed as well, so the element that used to be the next element in the list is not the next element after this change.

Alternatively, we can use a slicing operator and pass the list as iterable which makes the tracker remember the length of the list and the item being iterated.

iter_list = [1, 2, 3, 4, 5, 6]
for i in iter_list[:]:
    print(i)
    iter_list.remove(i)
print("empty list", iter_list)

# Output
1
2
3
4
5
6
empty list []

Iterating over a tuple using for loop

When we pass a tuple as an iterable into for loop, the body of the for loop is executed for each element of the tuple. Since a tuple is an immutable data type, we can only access and if we want to operate on the elements we can assign them to another variable.

tuple_seq = (1, 2, 3)
for i in tuple_seq:
    print(i)

# Output
1
2
3

Iterating over a string using for loop

If we pass a string as an iterable into for loop, the body of the loop is executed for each character of the loop while loading one character after the other into the variable of the loop as the string gets iterated.

for i in "Hello WorlD":
    # prints only upper case letters
    if i.isupper():
        print(i)

# Output
H
W
D

Iterating over a set using for loop

If we pass a set as an iterable into for loop, the body of the loop is executed for each character of the loop while loading one element after the other into the variable of the loop as the set gets iterated.

In sets, the order is not preserved for the elements thus elements returned while each iteration might be in a different order than expected.

set_seq = {"hello", "Welcome", "python"}
for i in set_seq:
    print(i)  

# Output
Welcome
python
hello

Since the set is a mutable type, we have to be careful while updating the set because of memory being revised and the tracker losing the element being iterated. Alternatively, we can use the slicing operator as we used in the previous example of lists.

Iterating over a dictionary using for loop

Iterating and accessing the items of a dictionary is different as compared to other sequence types. Since the dictionary has key-value pairs as items, we need in-built methods to access the items of the dictionary.

dict_seq = {"Hello" : "World", "Welcome" : "python", "level" : "easy"}
for i in dict_seq:
    print(i)  

# Output
Hello
Welcome
level

To access both key and value pairs of the dictionary we can use the .items() method which returns both key-value as items so that they can be iterated.

dict_seq = {"Hello" : "World", "Welcome" : "python", "level" : "easy"}
for i in dict_seq.items():
    print(i)  

# Output
('Hello', 'World')
('Welcome', 'python')
('level', 'easy')

.keys() is used to return keys of the dictionary as iterable.

for i in dict_seq.keys():
    print(i)  

# Output
Hello
Welcome
level

.value() is used to return values of the dictionary as iterable.

for i in dict_seq.values():
    print(i)  

# Output
World
python
easy

Enumerate in for loops

enumerate() in python takes a sequence as a parameter and provides a counter to each element of the sequence. Each element is stored along with its counter as an index in a tuple.

list_seq = ["a", "b", "c", "d"]
for i in enumerate(list_seq):
    print(i)  

# Output
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')

This counteracts as an index to the items of the sequence. We can also pass counter and element as separate variables by declaring two variables in the header of the for loop.

list_seq = ["a", "b"]

# Returns the counters( index ) of the elements
for index, element in enumerate(list_seq):
    print(index)  

# Output
0
1

# Returns elements
for index, element in enumerate(list_seq):
    print(element)  

# Output
a
b

By default, the index starts from “0” if we don’t pass any start value. We can customize the start value so that the indexing starts from the start value and is incremented by +1 for each iterable item.

The start value has to be only an integer but can be either +ve or -ve.

for index, element in enumerate(list_seq, 5):
    print(index, element)  

# Output
5 a
6 b
7 c
8 d

zip using for loop

zip() is a python in-built function to iterate over two iterables simultaneously. It stores the items at equal positions as a tuple. Thus forms a set of tuples as a sequence to be iterated.

Elif 11
zip_obj1 = [1, 2, 3]
zip_obj2 = [1, 2, 5]
print(zip(zip_obj1, zip_obj2))

# Output
<zip object at 0x00000179F6C165C0>

Since we have passed two objects into the zip function, the tuples inside the zip object each of them will have elements that are selected from equal indices.

print(list(zip(zip_obj1, zip_obj2)))   -> [(1, 1), (2, 2), (3, 5)]

This zipped object can then be used as an iterable in for loop to print the elements inside the tuple. To retrieve values from each tuple of the zip object we need to declare two variables in the header of the for a loop.

zip_obj1 = [1, 2, 3]
zip_obj2 = [1, 2, 5]
for obj1, obj2 in zip(zip_obj1, zip_obj2):
    print(obj1, obj2)

# Output
1 1
2 2
3 5

If we pass objects of different lengths into the zip() function the number of tuples being formed is based on the number of items in the smallest object.

The excess elements are left behind and will not be selected.

Elif 12
zip_obj1 = [1, 3, 4, 5, 6]
zip_obj2 = [1, 2, 5]
for obj1, obj2 in zip(zip_obj1, zip_obj2):
    print(obj1, obj2)

# Output
1 1
3 2
4 5

sorted() method in for loop

sorted() is an inbuilt method in python that returns an object with sorted items. By default if the items are numbers they are arranged in ascending order, if they are strings then the characters of the string are arranged in lexicological order.

In the below scenarios, we use sorted() method in for loop

  • When we need to get a sorted copy of an iterable of a mutable type without mutating (changing) the original iterable
  • If we need to get a sorted copy of an iterable of an immutable data type (for example, a tuple).
list_obj = [6, 5, 1, 2, 1]
for i in sorted(list_obj):
    print(i, end=",")

# Output
1,1,2,5,6

We can also use sorted() to return the copy of an object with items in descending order.

By default, the reverse parameter is set to False. If we set the parameter reverse = True then it reverses the order into descending order.

list_obj = [6, 5, 1, 2, 1]
for i in sorted(list_obj, reverse = True):
    print(i, end=",")

# Output
6,5,2,1,1,

While loops in python

while loops provide iterating over a block of code multiple times as long as the condition is True. It stops iterating when the condition is false. Unlike the for loops we have to make necessary changes so that eventually the loop will be terminated at some point.

If the condition is always True then the loop is iterated for an infinite number of times known as an infinite loop.

App Seqdeployement 2

Applications of while loop:-

  • We can start execution of a program by having while loop in the start. If the user provides a valid input which satisifes the condition of the loop, then the program is executed, else it terminates the execution
  • We use While Loops in search algorithms like Binary Search because we cannot know in advance how many iterations it will take for the program to find the item that is being searched
  • Games typically have a main While Loop that keeps the program running until the player runs out of lives or until another event causes the game to end

The syntax of the while loop starts with the header of the loop and then the body of the loop. The header of the while loop has a condition that is evaluated to return either True or False to continue running the while loop.

Same as the for loop the header of the while loop also ends with an indent. All the statements that we write under the indent belong to the while loop and statements that we write outside the indent do not belong to the body of the loop.

while <condition>:
   # Body of the loop
  • A while loop does not have a fixed number of iterations. It runs indefinitely until the condition is False. Thus while loop are used when we don’t know how many times a loop has to run.
  • While loops also don’t update the variable in the condition automatically, so we have to adjust the values by assigning it few operations so that for each iteration the variable gets updated.
  • If the variable in the condition is not updated and the condition returns True, then loop is turned out into infinite loop.

In the below example for starting the while loop, the condition is evaluated first, Since it’s True the loop is repeated with the variable being incremented.

This loop repeats till the condition is True, after a few iterations the incremented value of the variable does not satisfy the condition thus the loop is terminated.

i = 0
while i < 5:
    print(i)
    i += 1

# Output
0
1
2
3
4

In some cases when the condition is for starting the loop turns out to be false then the loop is not executed.

i = 20
while i < 5:
    print(i)
    i += 1

The below is an example to print odd numbers between 50 and 25 in descending order using a while loop.

i = 50
while i >= 25:
    if i%2 != 0:
        print(i, end = " ")
    i = i - 1

# Output
49 47 45 43 41 39 37 35 33 31 29 27 25

Nested While loops

Nested while loops are a while loop inside another while loop. We use them when each iteration of the loop, we need to repeat some action for an unknown number of times.

Here is the syntax of the nested while loops. The condition of each while loop is written in its respective headers.

while <condition 1>:
    <statements>
    while <condition 2>:
        <statements>
Nested While 2 1

Transfer statements break, Continue

These Transfer statements are known as loop control statements, which change the behavior of the loop. They change the normal flow of the loop.

break statement

The break statement is used to break the iteration and exit the loop based on the condition.

When the interpreter reads a break statement inside any loop then the iteration of the loop is stopped at that point and any lines declared inside the loop after the break statement is not executed. The control is passed to statements after the loop.

for i in <sequence>:
    # Statements
    if condition:
        break

This break statement can be declared inside a condition such that when the condition is evaluated to be true and we would like to stop the next iteration and come outside of the loop.

In the below example, the if condition checks the value of i for every iteration. After 4 iterations during the 5th iteration that value of i = 5 ( i > 4 ). The condition is satisfied and the body of the condition is executed.

Since in the body of the if clause we have a break, thus the control comes out of the loop. Any statements in the loop after executing the break are not evaluated by the interpreter.

for i in range(1, 50):
    if i > 5:
        print("loop will be terminated")
        break
    print(i)
print("Outside for loop")

# Output
1
2
3
4
loop will be terminated
Outside for loop

The same break statement can be implemented in the while loops. After few iterations when the value of the variable in the condition of the while loop has reached a certain value and we would like to stop iteration at that point we declare break.

user_data = []
while True:
    input_data = int(input("enter only positivie numbers:"))
    if input_data < 0:
        break
    user_data += [input_data]
print(user_data)

# Input
enter only positivie numbers:2
enter only positivie numbers:6
enter only positivie numbers:1
enter only positivie numbers:-4

# Output
[2, 6, 1]

break statement in nested loops

The break statements inside nested loops, break the iteration of the innermost loop, in simple terms break statement is confined to the loop in which it was declared.

If the break statement is declared inside an outer loop then execution of the outer loop is terminated. If the break statement is inside an inner loop then the inner loop is terminated and the next iteration of the outer loop is performed.

# breaks the inner for loop
for i in <iterable_1>:
    for j in <iterable_2>:
        break

# breaks the inner while loop
while <condition_1>:
    while <condition_2>:
        break

As we know when we declare break inside an inner loop and after stopping the iteration of the inner loop by break statement, the control is passed to the next iteration of the outer loop.

In the next iteration again inner loop is executed on all its iterable and if the condition associated with the break is satisfied then again control is passed to the next iteration of the outer loop.

for i in range(2):
    for j in "hello":
        if j == "l":
            break
        print(i, j)

# Output
0 h
0 e
1 h
1 e

Continue statement

The continue statement is used when we would like to skip the current iteration and pass the control to the next iteration without breaking the loop.

If the interpreter reads a continue statement inside any loop then the iteration of the loop is skipped at that point and any lines declared inside the loop after the continue statement is not executed in that particular iteration. Control is passed to the next iteration.

for i in <sequence>:
    # Statements
    if condition:
        continue

This continue statement can be declared inside a condition such that when the condition is evaluated to be true and we would like to stop the current iteration and pass the control to the next iteration.

In the below example, we have a sequence of numbers from 0 to 9. When the value of the variable is even and we don’t want to perform operations using an even number we can simply declare a continue statement associated with a condition.

Thus iterations are performed only using odd numbers.

for i in range(9):
    if i % 2 == 0:
        continue
    print(i)

# Output
1
3
5
7

The functionality of the continue is the same when used in the while loop. The current iteration is skipped and control is passed to the next iteration.

i = 0
while i < 10:
    i += 1
    if i % 2 == 0:
        continue
    print(i)

# Output
1
3
5
7
9

Continue statement inside nested loops

When a continue statement is declared inside a nested loop that means the current iteration of the inner loop is skipped and the next iteration of the inner loop is executed.

The presence of a continue statement inside an inner loop does not affect the flow of the outer loop. Also, the code written after the continue statement is not executed.

In the below example, the program does not execute the print statement when the iterable value of the inner loop is an even number. It skips the current iteration of the inner loop and goes to the next item in the sequence of the inner loop.

This operation is repeated till all the items of the outer loop are iterated.

for i in "AB":
    for j in range(4):
        if j % 2 == 0:
            continue
        print(i, j)

# Output
A 1
A 3
B 1
B 3

else clause with loops

The else clause is executed when the iteration of a loop is completely exhausted. When we have an else clause after a loop and also an if condition inside the loop, then it does not mean the else clause is associated with the if block. It rather is associated with the loop.

There are certain conditions to execute an else block associated with a loop. These conditions are applicable for both for and while loops

  • if the break statement associated with loop is not executed then the else clause is executed
  • if there is no break statement in the loop then else block is executed

In the below code, we have two examples where the break statement is executed in the first example results in the interpreter skipping the else block. In the second example even though the break statement is present but not executed, the else clause is executed.

# break statement executed
# else block not executed
for i in "AB":
    print(i)
    if i == "B":
        break
else:
    print("loop completed")
# Output
A
B


# break statement not executed
# else block executed
for i in "AB":
    print(i)
    if i == "C":
        break
else:
    print("else block")
# Output
A
B
else block

If there is no break statement in the loop then the else block is executed.

for i in "AB":
    print(i)
else:
    print("loop completed")

# Output
A
B
loop completed

FAQ’s in Python loops

How to loop through a dictionary in python?

As for loop can iterate over any sequence of values since the dictionary is also a sequence we can pass it as an iterable into for loop. Based on our requirement of iteration we can use different methods such as dict.items(), dict.values(), dict.keys().

In the below example we simply pass a dictionary which makes for loop to iterate over the keys of the dictionary.

dict_seq = {"Hello" : "World", "Welcome" : "python", "level" : "easy"}
for i in dict_seq:
    print(i)

# Output
Hello
Welcome
level

How to loop through values in a dictionary python?

To loop over the values of a dictionary we can pass dict.values() as a sequence since it returns only the values as iterables.

dict_seq = {"Hello" : "World", "Welcome" : "python", "level" : "easy"}
for i in dict_seq.values():
    print(i)

# Output
World
python
easy

How to end a while loop in python?

While loop runs iteratively as long as the condition is evaluated to True. We have to create a while loop such that after a few iterations the condition would become False and end the loop.

loop_variable = 0
while loop_variable < 5:
    print(loop_variable)
    loop_variable += 1

Alternatively, we can also add a break keyword which can terminate the iteration of the loop.

How to loop through a list in python?

To loop through a list we can use for loop which uses sequences as iterables. On every iteration, the for loop iterates over the items of the list, till all the items have been iterated.

my_list = [1, 2, 3, 4]
for i in my_list:
    print(i)

# Output
1
2
3
4

How to end a for loop in python?

The main functionality of for loop is to iterate over all the iterables that have been passed as a sequence. The iterator keeps track of items that have been iterated and yet to be iterated.

Once all the iterables are iterated automatically the for loop is ended. Alternatively, we can also add a break keyword which can terminate the iteration of the loop.

How to break out of a while loop python?

To stop a while loop we can use the break keyword which exits the loop. Thus the iteration is stopped at that point and control is passed to the next lines of code declared after the while loop.

a = 0
while a < 4:
    if a == 2:
        break
    a +=1
print("loop ended")

# Output
loop ended

How to break out of a for loop in python?

To break out of a for loop we can use the break keyword which can be associated with a condition, such that when the condition is evaluated to True then iteration of the loop will be ended.

my_list = [1, 2, 3, 4, 5]
for i in my_list:
    if i > 3:
        break
    print(i)

# Output
1
2
3

How to reverse a string in python using for loop?

To reverse a string we can parse it from the end. During each iteration, the one item from the string in reverse order is passed to the loop variable. This value can be used inside the body of the loop to build a new string which will be exactly the reverse of the string.

my_string = "hello world"
rev_string = ""

# Using slicing concept
my_str = "hello world"
rev_str = ""
my_str_length = len(my_str) - 1
for i in range(my_str_length, -1, -1):
    rev_str = rev_str + my_str[i] 
print(rev_str)

# Output
dlrow olleh


# Using my_string as sequence
for i in my_string:
    rev_string = i + rev_string
print(rev_string)

# Output
dlrow olleh

How to stop an infinite loop in python?

When the execution of the program has entered into an infinite loop there will not be any end result returned by the program, rather it keeps executing the same piece of code again and again.

To stop an infinite loop in such cases we can either stop the program execution or implement a line code that can accept a keyboard interruption which will end the execution.

How to reverse a list in python using for loop?

To reverse a list we can parse it from the end. During each iteration, the one item from the list in reverse order is passed to the loop variable. This value can be used inside the body of the loop to build a new list which will be exactly the reverse of the list.

my_list = [1, 2, 3, 4, 5]
rev_list = []
for i in range(len(my_list)):
    rev_list= [my_list[i]] + rev_list
print(rev_list)

# Output
[5, 4, 3, 2, 1]

How to loop a certain number of times in python?

To loop a certain number of times we can use range() function. In the range function we can define the number of times we would require a loop to run.

for i in range(2):
    print(i)

# Output
0
1

How to use range in for loop python?

range() function returns integers that lie under start and stop value. The parameters that we pass into range are start, stop, step. By default, the start and step values are 0 and 1 respectively. We can customize these start, stop, step values.

for i in range(1, 10, 2):
    print(i)

# Output
1
3
5
7
9

How to create an infinite loop in python?

We can use a while loop with True condition. This makes the loop iterate an infinite number of times.

If a loop does not have a termination condition then it results in an infinite loop.

while True:
    # Statements

How to count how many times a loop runs python

We can create a count_variable with a 0 value at the beginning of the loop. After the loop completes one successful iteration we need to increment the value by +1, thus for each iteration the value stored by the count_variable tells us how many times the loop is iterated.

count_variable = 0
for i in range(1, 5):
    count_variable += 1
print(count_variable)

# Output
4

How to get index in for loop python?

In python, enumerate() method adds an index value to each item of a sequence that we pass into it. We can retrieve these elements along with their indices using for loop, in which each iteration returns an element and its index as a tuple.

my_list = ["a", "b", "c"]
for i in enumerate(my_list):
    print(i)

# Output
(0, 'a')
(1, 'b')
(2, 'c')

How to reverse a number in python using for loop?

num = int(input())
rev_num = ""
for i in str(num):
    rev_num = i + rev_num
print(int(rev_num))

# Input    # Output
 24235       53242

How to skip an iteration in a loop in python?

To skip an iteration python provides a continue keyword. The continue statement is used when we would like to stop the current iteration and pass the control to the next iteration without breaking the loop.

for i in range(9):
    if i % 2 == 0:
        continue
    print(i)

# Output
1
3
5
7

How to go back to the beginning of a loop in python?

continue keyword brings control back to the start of the loop. When the continue statement is executed by the iterator the code after the continue is not executed rather control is passed to start of the loop

for i in range(3):
    if i == 1:
        continue
    print(i)

# Output
0
2

What is a nested for loop in python?

Nesting of the for loops is done when for each iteration of the loop we need to repeat an action a particular number of times.

The condition of the outer for loop checks whether there are items to be iterated or not, once it is evaluated to True then the control is passed to the body of the outer for loop.

for i in range(2):
    for j in range(1, i+2):
        print(i, j)
# Output
0 1
1 1
1 2

How to write an if statement inside a loop in python?

We can write an if statement inside any loop when we write it under the indent of the loop. This if conditional will be checked for every iteration of the loop.

for <var> in <iterable>:
    if <condition>:
        # statements

How to create a for loop without any parameters python?

We can create a loop without any parameters also. Instead of declaring a loop variable we can just use underscore (” _ “). This underscore does not store the value of the iterable it just keeps the loop to be iterated till all the iterable are exhausted.

for _ in range(2):
    print("for loop")

# Output
for loop
for loop

How can i make it so user inputs to and while loop stops python?

If we provide the condition of the while loop to be True then the loop keeps on iterating till any external interruption has occurred. So, when we implement a conditional statement that could break the loop based on user input could stop the iteration of the while loop.

while True:
    if input() == "break":
        break
    print("executed")
print("terminated")

# Input   # Output
   f       executed
   wx      executed
 break     terminated

How do i make a loop do nothing in python?

When we want a loop to do nothing, but it could be possible to use it in the future then we can use a pass statement inside a loop. This pass statement does nothing it simply passes the execution.

for <var> in <iterable>:
    pass

In case if we try to do the same in a while loop we may end up in an infinite loop.

When would you put a while loop inside a for loop python?

A while loop is used when we don’t know how many times the same set of instructions has to be executed.

When each value of the sequence has to undergo the same set of definite iterations, we can pass the sequence into a for loop and each iterable item to be iterated using a while loop.

for i in range(2, 3):
    multiple = 1
    while multiple < 5:
        print(f"{i} x {multiple} = {i * multiple}")
        multiple = multiple + 1

# Output
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8

When would you use a nested loop in python?

Nested loops are used in nested Collections, a Matrix, a Table of a table, print star, or number patterns.

How to do a backwards range for loop in python?

To make range() function return values in backward order when we define the step of the range to be negative.

for i in range(6, 1, -1):
    print(i)

# Output
6
5
4
3
2

In python, how to write a for loop but skip certain elements?

To skip certain iterations in python we need to use the continue keyword. This continue keyword has to be associated with a condition that can check whether it can be skipped for iteration or not.

new_str = "Hello World"
for i in new_str:
    if i.isupper():
        continue
    print(i, end = "")

# Output
ello orld

In python, how to loop over a list of dictionaries to print key-value pairs?

To loop over a list of dictionaries and print all the key-value pairs, we need to use the nested loops concept. The outer loop iterates over the list of dictionaries, and the inner loop iterates over each dictionary to print the key-value pairs.

dict.items() returns both key and value as pairs.

dict_1 = {1 : "a", 2 : "b"}
dict_2 = {3 : "c", 4 : "d"}
dict_3 = {5 : "e", 6 : "f"}
list_dict = [dict_1, dict_2, dict_3]
for i in list_dict:
    for j in i.items():
        print(j)

# Output
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')
(6, 'f')

In python, stop a loop when the length of a list is 0?

Iterate list using for loop, if there are zero items in the list for-loop automatically gets terminated.

my_list = [1, 2, 3, 4]
for i in my_list:
    print(i)

# Output
1
2
3
4

We can create a while loop with the condition as len(list) > 0, such that on each iteration the length of the list is monitored and terminates the loop if the length of the list is 0.

my_list = [1, 2, 3, 4]
while len(my_list) > 0:
    print(my_list.pop())

# Output
4
3
2
1

How to get the next item in loop python?

While operating in a loop, .next() returns the next item that is going to be iterated.

my_list = iter([1, 2, 3, 4])
for i in my_list:
    print(i, next(my_list))

# Output
1 2
3 4

How to loop over multiple variables in python?

We can loop over multiple variables simply passing them as iterable items. Each iteration on a variable will be iterated.

var_1 = "hello"
var_2 = "python"
var_3 = 3.8
for i in var_1, var_2, var_3:
    print(i)

# Output
hello
python
3.8

How to loop that prints each number and its square on a new line python?

We can pass a list of numbers as iterable objects into a for loop. On each iteration, we can print the number and square of its value.

list_seq = [2, 3, 5, 4, 8]
for i in list_seq:
    print(i, " squared value is", i * i)

# Output
2 squared value is 4
3 squared value is 9
5 squared value is 25
4 squared value is 16
8 squared value is 64

How to print odd numbers in a for loop python?

While iterating over a list of integers we can check whether a number is even or odd by using the modulus operator ( % ). We can associate a print statement with the condition being to print only numbers when divided by 2 and do not return 0 as the remainder.

list_seq = [1, 2, 3, 5, 4, 8, 10, 11]
for i in list_seq:
    if i % 2 != 0:
        print(i)

# Output
1
3
5
11

How to loop reversely through a list in python?

To loop reversely through a list we need to iterate over the list from the last item to the first item.

list_seq = [1, 2, 3, 5]
for i in range(len(list_seq) - 1, -1, -1):
    print(list_seq[i])

# Output
5
3
2
1

We can also use reversed(list) to reverse the list and then iterate over the list.

How to break from double while loop in python?

We can assign a flag value such that for every iteration the value is incremented and when the flag value reaches a particular value then we break the loop with the help of the if clause.

The same value can be used with a condition in both the inner and outer loops.

flag_1 = flag_2 = 0
while True:
    if flag_1 > 9:
        break
    while True:
        if flag_2 > 5:
            break
        flag_2 = flag_2 + 1
    flag_1 = flag_1 + 1

How to add list numbers in python while loop?

list_seq = [1, 2, 3, 5]
count = sum_list = 0
while count < len(list_seq):
    sum_list = sum_list + list_seq[count]
    count = count + 1
print(sum_list)

# Output
11

How can i print even numbers from 1 to 100, using a for loop python?

To print all the even number between 1 to 100 we can use range(1, 101) as iterable and each value has to undergo modular division by 2 such that 0 remainder indicates even number.

for i in range(1, 101):
    if i % 2 == 0:
        print(i, end = ", ")

# Output
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, - - - 
- - - - 
84, 86, 88, 90, 92, 94, 96, 98, 100,

How to find the lowest score with a loop python?

We can use min(list_scores) to directly return the minimum value in the list.

But in case if we would like to have a loop we can use the below example.

list_scores = [25, 45, 89, 12, 34, 23, 80]
min_score = list_scores[0]
for i in list_scores[1:]:
    if i < min_score:
        min_score = i
print(min_score)

# Output
12

In python when to use while vs for loop examples?

  • for loop is used when we know how many times a loop has to be iterated. When we also need to loop over a sequence, the for loop provides easy iteration with few variables. for loop also improves readability of the code
  • While loop is used when we dont know how many times a loop has to be iterated.
  • The main advantage of a for loop over a while loop is readability. A For loop is a lot cleaner and a lot nicer to look at. It’s also much easier to get stuck in an infinite loop with a while loop.

How to print multiples of a number in python for loop?

num = 5
for i in range(1, 6):
    print(num * i)

# Output
5
10
15
20
25

Why does the order of keys in python changes with each edition of keys in loop to dictionary?

Generally, Regular Dictionaries are not ordered pairs. Thus indexing is also not allowed in dictionaries. Since the order is not there while adding new key-value pairs the order will not be the same.

If the dictionary is an ordered dictionary then the insertion order is preserved thus when edition of keys will not disturb the order.

How to print the upper case letters in a string using a while loop in python?

To print all the upper case letters in a string we need to iterate over the string and compare whether the iterating value is an upper case or not.

The number of iteration has to be equal to the length of the string.

new_string = "Hello WorlD"
count = 0
while count < len(new_string):
    if new_string[count].isupper():
        print(new_string[count])
    count = count + 1

# Output
H
W
D

How to generate a string using for loop iteration over a list in python

On each iteration, the iterating value has to be added to a new_string using a concatenation operator.

new_string = ""
for i in ["H", "E", "L", "L", "O"]:
    new_string = new_string + i
print(new_string)

# Output
HELLO

In python, how to know if its the final iteration of a loop?

We can create a count variable that can be incremented by a certain value on each iteration, so that when it is equal to the length of the items in the sequence then we reached the last item.

my_string = "HELLO"
count = 1
for i in my_string:
    if count == len(my_string):
        print("last iteration", count)
    count = count + 1

# Output
last iteration 5

How to loop through and remove every item from a list in python?

list.remove() removes the item that we are iterating from the list. To make memory track the number of items getting iterating we need to use a sliced sequence.

my_list = [1, 2, 3, 4, 5, 6]
for i in my_list[:]:
    my_list.remove(i)
print(my_list)

# Output
[]

Alternatively, we can also use the pop() method which removes each item from the list.

my_list = [1, 2, 3, 4, 5, 6]
for i in range(len(my_list)):
    my_list.pop()
print(my_list)

# Output
[]

How much memory does infinite while loop use python?

As long as the while loop keeps on running in an infinite loop, a certain amount of memory consumed for a single iteration will be kept on increasing till the system goes out of memory.

How to create loop with two conditions python?

It’s as simple as we create two conditions in a general program. Proper indentation of the loop has to be followed so that all the conditions are inside the body of the loop.

for <var> in <iterable>]:
    if <condition_1>:
         statements_1
    if <condition_2>:
         statements_2

How to add values to a dictionary in a loop python?

To add values to a dictionary in python we need to assign a key to a particular value. We can use count so that each iteration of increasing count value can be assigned as a key to a particular value.

dict_obj = {}
list_obj = ["hello", "world", "python"]
count = 1
for i in list_obj:
    dict_obj[count] = i
    count = count + 1
print(dict_obj)

# Output
{1: 'hello', 2: 'world', 3: 'python'}

How to use a for loop in python to count the number of characters in a sentence?

count variable can be used such that for every iteration the value of count is increment by +1 as we iterate over the characters of a sentence. This sentence has to be passed as a sequence into for loop.

In the below example, we ignored the counting of empty space so that only the character of the sentences are counted.

new_string = "Hello world, welcome to Python"
count = 0
for i in new_string:
    if i != " ":
        count = count + 1
print(count)

# Output
26

How to alter values of dict in for loop python?

dict_obj = {1: 'hello', 2: 'world', 3: 'python'}
list_obj = ["Welcome", "to", "program"]
count = 0
for i in dict_obj.keys():
    dict_obj[i] = list_obj[count]
    count = count + 1
print(dict_obj)

# Output
{1: 'Welcome', 2: 'to', 3: 'program'}

How to add integers to a list in python loop?

To add an integer into a list we can either use the list concatenation concept where each number will be concatenated to the list, or we can also use .append() method which appends the item into the list.

list_obj = ["Welcome", "to", "program"]

# Using append
for i in range(3):
    list_obj.append(i)
print(list_obj)

# Output
['Welcome', 'to', 'program', 0, 1, 2]

# Using list concatenation
for i in range(3):
    list_obj = list_obj + [i]
print(list_obj)

# Output
['Welcome', 'to', 'program', 0, 1, 2]

How do i write a pow function using a while loop in python?

In python math module provides pow() method which returns the result base raised to power.

import math
num = 5
print(math.pow(5, 3))

# Output
125.0

The below example provides the implementation power function in loops.

base, power = map(int, input().split(","))
def pow(base, power):
    count = 0
    value = 1
    while count < power:
        value = base * value
        count = count + 1
    return value
result  = pow(base, power)
print(result)

# Input    # Output
  5, 3        125

In python, why is index out of range with while loop

When we iterate over a loop, if we try to access or modify the non-existing index of a sequence then an error is returned mentioning the index out of range.

So, we have to try to access the elements using valid indexes, you can decide the valid indexes by retrieving the length -1 of the collection or sequence

How do i create a list of different strings in a for loop python?

In the below example repeated strings are not added to the list.

new_string = "hello welcome to my home hello start home cleaning"
new_list = []
for i in new_string.split(" "):
    if i not in new_list:
        new_list = new_list + [i]
print(new_list)

# Output
['hello', 'welcome', 'to', 'my', 'home', 'start', 'cleaning']

How to make a loop go from one iteration to the next after a certain amount of time in python?

We can use sleep() method which makes the interpreter wait for the completion of the command and then go for the next iteration.

import time
for i in range(2):
    time.sleep(2)
    print("after two seconds")

# Output
after two seconds
after two seconds

How to use enumerate in for loop python?

enumerate() function provides a counter to each item of the iterable. These counter and the item are stored as a tuple.

my_list  = ["hi", "hello", "welcome"]
for i in enumerate(my_list):
    print(i)

# Output
(0, 'hi')
(1, 'hello')
(2, 'welcome')

How to subtract two lists in python with for loop?

list_1 = [4, 5, 6]
list_2 = [1, 2, 3]
difference = []
for list1, list2 in zip(list_1, list_2):
    difference.append(list1 - list2)
print(difference)

# Output
[3, 3, 3]

How to use two loop variables in for loop python?

In a for loop, the choice of a number of loop variables to use is dependent on the number of items that an iterable returns on each iteration.

For example, dict.items() return both key and values which can be accessed by creating two loop variables.

dict_obj = {1: 'hello', 2: 'world', 3: 'python'}
for i, j in dict_obj.items():
    print(i, j)

# Output
1 hello
2 world

how to write for loop in python to get fibonacci ?

input_num = int(input())
a, b = 1, 2
for i in range(input_num):
    print(a, end = " ")
    a, b = b, a+b

# Output
10
1 2 3 5 8 13 21 34 55 89

What does for loop in range (a-1, -1, -1) mean python?

In range() the order of the parameter passed are start, stop, step. start + step is performed as long the values lie in the [a-1, -1].

for i in range(7, -1, -1):
    print(i, end = " ")

# Output
7 6 5 4 3 2 1 0

How to loop through a string 3 letters at a time in python?

To loop through a string and return 3 letters at a time we can use the slicing operator. the value inside the slice operator has to be swapped and incremented by 3 in each iteration.

In the Output, strings with three letters are printed. If a string has only two characters then the third character is an empty space.

loop_string = "There are mutable and immutables in Python"
a, b = 0, 3
len_string = len(loop_string)
for i in loop_string[:]:
    if b+3 > len_string:
        break
    print(loop_string[a : b], end = ",")
    a, b = b , b+3

# Output
The,re ,are, mu,tab,le ,and, im,mut,abl,es ,in ,Pyt,

How to write a factorial in python using for loop?

fact_num = int(input())
factorial = 1
for i in range(fact_num, 0, -1):
    factorial = factorial * i
print(factorial)

# Input    # Output
   6          720
   5          120

what is the sum of all even numbers between 19 and 35?

All the even numbers can be added to a previous value but the addition process has to be carried out only using even numbers. Thus all the statements of addition have to be associated with an if clause with conditions as even numbers.

sum = 0
for i in range(19, 35):
    if i % 2 == 0:
        sum = sum + i
print(sum)

# Output
216

How to use for loop in python to make a truth table?

Based on the truth table required by a user we can return the values of the truth table using for loop.

In the below example, the program returns the truth table of “and”, a similar process can be implemented for other operators(or, not) as well.

input_operator = input()
for i in True, False:
    if input_operator == "and":
        for j in True, False:
            print(f"{i} and {j} = {i and j}")

# Output
True and True = True
True and False = False
False and True = False
False and False = False

How to make while loop in python more efficient?

  • Rule number one: only optimize when there is a proven speed bottleneck. Only optimize the innermost loop. (This rule is independent of Python, but it doesn’t hurt repeating it, since it can save a lot of work. 🙂
  • Small is beautiful. Given Python’s hefty charges for bytecode instructions and variable look-up, it rarely pays off to add extra tests to save a little bit of work.
  • Use intrinsic operations. An implied loop in map() is faster than an explicit for loop; a while loop with an explicit loop counter is even slower.

How to find max value from a list in python using loop?

list_values = [25, 45, 89, 12, 34, 23, 80]
max_value = list_values[0]
for i in list_values[1:]:
    if i > max_value:
        max_value = i
print(max_value)

# Output
89

How to do a one line for loop in python?

We can create a one-line loop in python using the list comprehension concept. The result of each iteration is stored as an item in a list.

one_line = [i for i in range(3)]

# Output
[0, 1, 2]

How to loop through a integer in python?

To loop through an integer we need to type-cast the integer into string format such that each digit of the integer is passed as an item that can be used to perform operations.

int_number = 24235
for i in str(int_number):
    print(int(i))

# Output
2, 4, 2, 3, 5,

How to ask y/n to end program after loop runs python?

If we can collect a user input to be either y/n which can be associated with a break statement which can end the iteration and exit the loop.

for i in range(3):
    if input("do you want to exit:- ") == "yes":
        print("loop terminated")
        break
    else:
        print(i)

# Output
do you want to exit:- no
0
do you want to exit:- yes
loop terminated

Why wont my while loop work python?

The only reason which can stop the iteration of the while loop can be either there might be a statement that is making loop termination or else the condition of the loop is not satisfied to make iterations.

Which loop is faster in python?

In python, basically for loop shows to be faster than while loops. Also, the list comprehensions were faster than the ordinary for loop, which was faster than the while loop.

Simple loops are slightly faster than nested loops.

import time
start_time = time.time()
for i in range(100000):
    pass
end_time = time.time()
print(end_time - start_time)

# Output
0.012993
import time
start_time = time.time()
i = 0
while i < 100000:
    i = i + 1
end_time = time.time()
print(end_time - start_time)

# Output
0.035940