This tutorial will demonstrate three different ways that you can loop through data using Python. If you are unfamiliar with using Loops or would like a more detailed example click here for a For Loop tutorial.
Technique One
The first technique is enumerate() . Enumerate is used to get the index and corresponding
for i, suits in enumerate(['Heart','Diamond','Spade','Club']):
print(i,suits)
Output :
0 Heart
1 Diamond
2 Spade
3 Club
Technique Two
iteams() gets items from a dictionary
Cards = {'Queen': 'Jack ', 'King': 'Ace'}
for q , k in Cards.items():
print(q,k)
Output :
Queen Jack
King Ace
Technique Three
zip() is used to loop through two dictionaries
Cards = {'Queen', 'Jack ', 'King','Ace'}
suits = ['Heart','Diamond','Spade','Club']
for c, s in zip(Cards,suits):
print('{0} of {1}'.format(c,s))
Output :
Queen of Heart
Jack of Diamond
King of Spade
Ace of Club
One thought on “Python Tutorial : 3 Looping Techniques”