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:

Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

 

Looping techniques(Image Source: Author)

1. Looping through the sequence using enumerate():

When looping through a sequence like a list, tuple, range object, strings the position index and corresponding value can be retrieved at the same time using the enumerate() function.

enumerate()

enumerate(iterable, start=0)

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.

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:

To loop over two or more sequences at the same time, the entries can be paired with the 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.

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()

itertools.zip_longest(*iterables, fillvalue=None)

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.

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).

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.

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

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.

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:

  • Python version used in all examples: Python 3.8.1
  • 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.

My other blog links

Iterable vs Iterator in Python

Resources(Python Documentation):

Looping Techniques

enumerate()

zip()

for statements

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s