Python loops are pretty awesome. I’ve never been a big fan of loops because I always thought they were too complicated and I didn’t want to spend my time figuring out “the right way” to do them.
Fortunately, I think loops have become more intuitive in recent versions of Python, and I’ve learned a few new tricks that I want to share with you.

In this post, I’m going to share 4 python looping techniques that I find to be the most useful.

1. Looping over two lists at the same time

Have you ever wanted to loop over two lists at the same time?. This can be achieved using the zip() function.

colors = ["red", "blue", "white"]
types = ["warm", "cool", "neutral"]

for c, t in zip(colors, types):
    print(c + " is " + t)

Program Output:

red is warm
blue is cool
white is neutral

 

 

2. Using the enumerate() function.

When looping through a sequence (lists, tuple, string, etc), the position index and corresponding value can be retrieved at the same time using the enumerate() function.

colors = ["orange", "brown", "indigo", "black"]

for i, v in enumerate(colors):
    print(i , v)

Program Output:

0 orange
1 brown
2 indigo
3 black

 

The enumerate() function returns individual elements in the list with their indexes.

 

 

3. Looping through a dictionary with the items() method.

We can get both the keys and the corresponding values when looping over a dictionary by using the items() method.

grades = {'Ana': 'B', 'John':'A+', 'Denise':"A", "katy": 'A'}

for name, g in grades.items():
    print(name + " had " + g)

Program Output:

Ana had B
John had A+
Denise had A
katy had A

 

 

4. Reverse looping in Python.

To loop over a range of numbers in reverse order, first, specify the range and then call the reversed() function.

for r in reversed(range(7)):
    print(r)

Program Output:

6
5
4
3
2
1
0

 

The same analogy applies to looping over a list in reverse:

colors = ["blue", "red", "black", "yellow"]

for i in reversed(colors):
    print(i)

Program Output:

yellow
black
red
blue

 

Instead of implementing your own way of looping over two lists at the same time or looping reversely, these functions can save you lots of time. Knowing these little techniques and using them in your day-to-day programming can make you an efficient programmer. If you want to learn more Python, check out the best python courses on Udemy.