What is a loop?
We can think of loops as actions that return to the start after they have accomplished something.
Loops can be set up to iterate a fixed number of times, until a certain condition is met or they can even run infinitely (if you don’t tell them to stop).
There are two types of loops in Python, for loops and while loops.
Examples of for loops
The basic structure of a for loop in Python is:
for item in data_structure:
# code to execute for each item in the data_structure
Below are a few examples of how to iterate through different data structures in Python using a for loop:
Example 1: Loop through a tuple and print out each ‘tuple element‘
im_a_tuple = ("a", "b", "c")
for x in im_a_tuple:
print(x)
Example 2: Loop through a list and print out each ‘list element‘
im_a_list = ["a", "b", "c"]
for x in im_a_list:
print(x)
Example 3: Loop through a set and print out each ‘element’
im_a_set = set("abbccc")
for x in im_a_set:
print(x)
*Note that when iterating through a set the order of the elements in the set is not always maintained.
Example 4: Loop through a string and print out each ‘character’ or ‘string element’
im_a_string= "abc"
for x in im_a_string:
print(x)
Example 5: Loop through a dictionary and print out each key-value pair
dictionary = {'a': 'is for aardvark', 'b': 'is for beetle', 'c': 'is for camel'}
for key in dictionary:
print(key, dictionary[key])
In a dictionary items are arranged in key-value pairs. Note that the order of these pairs is not guaranteed, only the key-value pair information is retained.
Examples of while loops
A while loop is usually used to iterate over a sequence of values when the number of iterations is not known in advance.The basic structure of a while loop is:
while condition:
# code to execute while condition is true
Now a few examples of while loops.
Example 1:
Using a while loop to print every element in a list
my_list = [1, 2, 3, 4, 5]
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
Example 2:
Using a while loop to print every character in a string
my_string = "hello, world!"
i = 0
while i < len(my_string):
print(my_string[i])
i += 1
Example 3:
The infinite loop
Just for fun, here is an example of an infinite while loop that prints the string “I will print forever”, forever…
while True:
print("I will print forever")
Are there alternatives to loops?
Yes! There are methods faster and more readable than using loops when working with large datasets.
For example list comprehensions, generator expressions or libraries such as Pandas or NumPy which can perform mathematical operations on entire arrays or vectors at once. We will visit these in another post!