Python Looping Techniques

In this Python article, we will discuss the different looping techniques which are generally used to iterate oover different data types.

1. Looping Techniques

In python, looping techniques are used in different sequential holders.

The main purpose of using different looping techniques is to iterate over a list, set, dictionary, or another compatible data type in a convenient and efficient manner.

Looping techniques provide great help in a variety of scenarios and in different competitive programming because it uses specific techniques in the code which has overall structure maintained by the loop.

Looping techniques are helpful for the user in situations where we need to access the elements one at a time and there is no need to manipulate the structure and sequences of the data.

We may classify Looping techniques in two categories:

  • Based on forms
  • Based on data structure
Python-Looping-techniques
Python-Looping-techniques

Lets discuss both the types in detail with their python code implementation.

2. Based on various forms

In this set, we have some forms of loop that a we can implement based on the nature of the loop and also depends on the location of condition within the loop body.

2.1. Infinite loop

Infinite loop refers to the use of while loop with condition always TRUE

If there are lines below the while loop, they will be executed after the program has dealt with the full execution or condition check of the while loop.

Note: In real world scenario our loops should always have a condition which breaks the execution of the loop, but this is for the demonstration how an infinite loop looks like.

# An infinite loop example
while True:  # we may write while(1)
  get_number = int(input("Give me a number input :"))
  print("Okay, so it is :", get_number)
Output
Give me a number input :45
Okay, so it is :45
Give me a number input :56
Okay, so it is :56
Give me a number input :78
Okay, so it is :78
Give me a number input :^CTraceback (most recent call last):
   File "/Users/hiteshgarg/IdeaProjects/personal/codingeek/Python/infiniteloop.py", line 3, in 
     get_number = int(input("Give me a number input :"))
 KeyboardInterrupt

2.2. Condition at the top

It works like a normal while loop (considering the loop has no break statement) but with the condition to be checked placed at its top.

# An example for while loop
count = 0
while(count <= 6):
  count = count + 1
  print("Hello", count)
Output
Hello1
Hello2
Hello3
Hello4
Hello5
Hello6

2.3. Condition at the bottom

Just like do while loop in other programming languages like C or Java, it ensures the statement inside the loop runs at least one time. It has the condition to check at the bottom of the loop.

while(1):
  age = input("Tell me your age ")
  print("Your age is :", age)
  restart = input("Should I ask you again?(Y/N) ")
  if restart == "N":
    break
Output
Tell me your age 10
Your age is :10
Should I ask you again?(Y/N) Y
Tell me your age 20
Your age is :20
Should I ask you again?(Y/N) N

2.4. Condition in the middle

The loop with the condition to be checked is in the middle which means that the break will be between the statements of the loop. This loop can be implemented as an infinite loop.

while(1):
  price = input("Enter integer value ")
  try:
    int(price)
    print("Valid input")
  except ValueError:
    print("Invalid input!!!")
    break
Output
Enter integer value 213
Valid input
Enter integer value 2324
Valid input
Enter integer value test            
Invalid input!!!

3. Based on data structure

In this set, we have some in-built data structure or function which can be used in the loop technique.

3.1. Using enumerate() in Python

While looping through sequence objects like list, tuple, range object, strings etc, enumerate() can be used to access the index number along with the value it holds.

Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from the start which defaults to 0) and the values obtained from iterating over iterable.

Python docs

Iterate through list

Lets implement an example to loop through a list using enumerate().

for id, thing in enumerate(['coding', 'geek', 'best', 'website']):
  print(id, thing)
Output
0 coding
1 geek
2 best
3 website

Example 2

for item in enumerate(['coding', 'geek', 'best', 'website']):
  print(item)
Output
(0, 'coding')
(1, 'geek')
(2, 'best')
(3, 'website')

Iterate through string

Lets implement an example to loop through a string using enumerate().

for id, thing in enumerate('code'):
  print(id, thing)
Output
0 c
1 o
2 d
3 e

Example 2

for item in enumerate('code'):
  print(item)
Output
(0, 'c')
(1, 'o')
(2, 'd')
(3, 'e')

3.2. Using sorted() to iterate over a sorted list

sorted() is not used to sort the container instead it only returns items of the container in a sorted way just for an instance.

Example to iterate list in an ascending sorted way.

values = [10, 50, 80, 20, 30, 40]
for value in sorted(values):
  print(value)
Output
10
20
30
40
50
80

Example 2 to iterate list in descending sorted way using reverse=True as the sorted method parameter.

values = [10, 50, 80, 20, 30, 40]
for value in sorted(values, reverse=True):
  print(value)
Output
80
50
40
30
20
10

3.3. Using zip() to iterate

If we want to combine two similar data types, like a list with another list or a dictionary with another dictionary. We can use the zip method which will return the values in a particular sequence.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.

Python docs

Note: If the two iterables are of different sizes then the final result will skip the extra elements from the iterable with extra elements. For example ghanshyam in the example below.

names = ['ram', 'shyam', 'arman', 'ghanshyam']
surnames = ['verma', 'sharma', 'gupta']
for name, surname in zip(names, surnames):
  print(name, surname)
Output
ram verma
shyam sharma
arman gupta

3.4. Using items() to iterate over dictionary

items() is used to access the key-value pair of the dictionary in a continuous manner when it loops through the dictionary.

fruits = { "grapes":"green","apple":"red","mango":"yellow" }
for name,colour in fruits.items():
  print (colour,name)
Output
green grapes
red apple
yellow mango

So what are the benefits of using all these iteration techniques.

  • These four techniques reduce user efforts to code, are quick to implement.
  • It does not require any change in space holder and it makes the code efficient using for loop & while loops.

4. Conclusion

In this article we learned about

  • Looping techniques in Python
  • Looping techniques based on various forms
  • Looping techniques based on data structure

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index