Looping Techniques in Python

Let’s learn about looping techniques using functions like enumerate, zip, sorted, reversed in python.

Photo by Oliver Hale on Unsplash

Looping techniques:

Looping techniques(Image Source: Author)

1. Looping through the sequence using enumerate():

enumerate()

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 start which defaults to 0) and the values obtained from iterating over iterable. — Python docs

Looping through the list using enumerate():

Example 1:

Looping through the list using the enumerate() function returns a tuple containing count and value from the iterable. By default, the count starts from 0.

colors=['red','green','blue']
for color in enumerate(colors):
print (color)
#Output:
(0, 'red')
(1, 'green')
(2, 'blue')

Example 2:

colors=['red','green','blue']
for index,color in enumerate(colors):
print (index,color)
'''
Output:
0 red
1 green
2 blue
'''

Example 3:

The start is mentioned as 5. So count starts from 5 while looping through the iterable.

colors=['red','green','blue']
for color in enumerate(colors,5):
print (color)
'''
Output:
(5, 'red')
(6, 'green')
(7, 'blue')
'''

Looping through strings using enumerate():

Example 1:

Looping through the string using the enumerate() function returns a tuple containing count and value from the iterable. By default, the count starts from 0.

s='python'
for
i in enumerate(s):
print (i)
'''
#Output:
(0, 'p')
(1, 'y')
(2, 't')
(3, 'h')
(4, 'o')
(5, 'n')
'''

Example 2:

s="python"
for
i,j in enumerate(s):
print (i,j)
'''
#Output:
0 p
1 y
2 t
3 h
4 o
5 n
'''

Example 3:

The start is mentioned as 10. So count starts from 10 while looping through the iterable.

s='python'
for
i in enumerate(s,start=10):
print (i)
'''
#Output:
(10, 'p')
(11, 'y')
(12, 't')
(13, 'h')
(14, 'o')
(15, 'n')
'''

2. Looping through two or more sequences using zip() function:

zip()

zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

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

Looping through two sequences of the same length using zip()

Example 1:

num = [1, 2, 3]
colors= ['red', 'blue', 'green']
for i in zip(num, colors):
print(i)

'''
Output:
(1, 'red')
(2, 'blue')
(3, 'green')
''

Example 2:

n1=['color','fruits','numbers']
n2=['red','apple','one']
for i in zip(n1,n2):
print (i)
'''
Output:
('color', 'red')
('fruits', 'apple')
('numbers', 'one')'
'''

Looping through two sequences of different length using zip()

If looping through two sequences of different lengths using zip () means it stops when the shortest iterable is exhausted.

Example 1:

colors=['red','green','blue']
num=[1,2,3,4,5,6,7,8,9,10]
for i in zip(colors,num):
print (i)
'''
Output:
('red', 1)
('green', 2)
('blue', 3)
'''

Looping through two or more sequences using zip():

Example 1:

colors=['red','apple','three']
num=[1,2,3]
alp=['a','b','c']
for i in zip(colors,num,alp):
print (i)
'''
Output:
('red', 1, 'a')
('apple', 2, 'b')
('three', 3, 'c')
'''

3. itertools.zip_longest()

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.-python docs

Looping through two sequences of different lengths using itertools.zip_longest()

Example 1:

Not specifying the fillvalue, the default will be None.

from itertools import zip_longest
colors=['red','apple','three']
num=[1,2,3,4,5]
for i in zip_longest(colors,num):
print (i)
'''
Output:
('red', 1)
('apple', 2)
('three', 3)
(None, 4)
(None, 5)
'''

Example 2:

Specifying the fillvalue.

from itertools import zip_longest
colors=['red','apple','three']
num=[1,2,3,4,5]
for i in zip_longest(colors,num,fillvalue='z'):
print (i)
'''
Output:
('red', 1)
('apple', 2)
('three', 3)
('z', 4)
('z', 5)
'''

4. Looping through the sequence in sorted order using sorted() function:

sorted():
Return a new sorted list from the items in iterable.

Example: 1

Looping through the sequence (list) in sorted order(ascending order) using sorted () function.

num=[10,5,20,25,30,40,35]
for i in sorted(num):
print (i)
'''
Output:
5
10
20
25
30
35
40
'''

Example 2:

Looping through the sequence (list) in sorted order(descending order) using sorted () function.

num=[10,5,20,25,30,40,35]
for i in sorted(num,reverse=True):
print (i)
'''
Output:
40
35
30
25
20
10
5
'''

Example 3:

colors=['red','green','blue','yellow']
for i in sorted(colors,reverse=True):
print (i)
'''
Output:
yellow
red
green
blue
'''

Example 4:

Looping through the dictionary in sorted order(ascending order) using sorted () function. By default, it will sort the keys in the dictionary.

d={'f':1,'b':4,'a':3,'e':9,'c':2}
for i in sorted(d.items()):
print (i)
#Output:
('a', 3)
('b', 4)
('c', 2)
('e', 9)
('f', 1)

Example 5:

Looping through the dictionary in sorted order using the sorted function. Using the key parameter in the sorted function, to sort the dictionary based on its values.

Refer to my story for sorting based on the key parameter.

d={'f':1,'b':4,'a':3,'e':9,'c':2}
#sorting by values in the dictionary
for i in sorted(d.items(),key=lambda item:item[1]):
print (i)

#Output:
('f', 1)
('c', 2)
('a', 3)
('b', 4)
('e', 9)

5. Looping through the sequence using reversed() function:

reversed

reversed(seq)

Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).-Python docs

Example 1:

To loop over a sequence in reverse, and then call the reversed() function.

colors=['red','green','blue','yellow']
for i in reversed(colors):
print (i)
'''
Output:
yellow
blue
green
red
'''

6. Looping through a dictionary.

Example 1:

d={'a':1,'b':2,'c':3}
for k,v in d.items():
print (k,v)
#Output:
a 1
b 2
c 3

7. Modifying Collections while Iterating:

Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straightforward to loop over a copy of the collection or to create a new collection.- for loop

Strategy 1:Iterate over a copy

If we want to delete the items in the dictionary while iterating, iterate over a copy of the dictionary.

d={'a':1,'b':2,'c':3}
for k,v in d.copy().items():
if v%2==0:
del d[k]
print (d)
#Output:{'a': 1, 'c': 3}

Strategy 2: Create a new collection

d={'a':1,'b':2,'c':3}
d1={}
for k,v in d.items():
if v%2!=0:
d1[k]=v
print (d1)
#Output:{'a': 1, 'c': 3}
print (d)
#Output:{'a': 1, 'b': 2, 'c': 3}

Conclusion:

  • zip() -Looping over two or more iterables until the shortest iterable is exhausted.
  • zip_longest()-Make an iterator that aggregates elements from each of the iterables. Iteration continues until the longest iterable is exhausted.

If you like to read more of my tutorials on Python and Data Science,
follow me on medium.

Thanks for reading!

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data…

Sign up for Analytics Vidhya News Bytes

By Analytics Vidhya

Latest news from Analytics Vidhya on our Hackathons and some of our best articles! Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Indhumathy Chelliah

Written by

Machine Learning | Artificial Intelligence | Python https://indhumathychelliah.com/

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Indhumathy Chelliah

Written by

Machine Learning | Artificial Intelligence | Python https://indhumathychelliah.com/

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store