In this short tutorial, you will learn how to use loops more effectively in different situations.
Looping over two lists at the same time.
You might want to iterate/loop over two lists or sequences 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
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.
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
Reverse looping.
To loop over a range of numbers in reverse, 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
0 Comments
Leave a comment