Table of Contents
1 Loops
1.1 For
1.2 While
2 Break
3 Continue
4 List Comprehensions
Loop#
[1]:
import os
from IPython.core.display import HTML
def load_style(directory = '../', name='customMac.css'):
styles = open(os.path.join(directory, name), 'r').read()
return HTML(styles)
load_style()
[1]:
Loops#
For#
for variable in something:
algorithm
[2]:
for i in range(5):
print(i)
0
1
2
3
4
In the above example, i iterates over the 0,1,2,3,4. Every time it takes each value and executes the algorithm inside the loop. It is also possible to iterate over a nested list illustrated below.
[3]:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list1 in list_of_lists:
print(list1)
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
A use case of a nested for loop in this case would be,
[4]:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list1 in list_of_lists:
for x in list1:
print(x)
1
2
3
4
5
6
7
8
9
While#
while some_condition:
algorithm
[5]:
i = 1
while i < 3:
print(i ** 2)
i = i+1
print('Bye')
1
4
Bye
Break#
As the name says. It is used to break out of a loop when a condition becomes true when executing the loop.
[6]:
for i in range(100):
print(i)
if i>=7:
break
0
1
2
3
4
5
6
7
Continue#
This continues the rest of the loop. Sometimes when a condition is satisfied there are chances of the loop getting terminated. This can be avoided using continue statement.
[7]:
for i in range(10):
if i>4:
print("The end.")
continue
elif i<7:
print(i)
0
1
2
3
4
The end.
The end.
The end.
The end.
The end.
List Comprehensions#
Python makes it simple to generate a required list with a single line of code using list comprehensions. For example If i need to generate multiples of say 27 I write the code using for loop as,
[8]:
res = []
for i in range(1,11):
x = 27*i
res.append(x)
print(res)
[27, 54, 81, 108, 135, 162, 189, 216, 243, 270]
Since you are generating another list altogether and that is what is required, List comprehensions is a more efficient way to solve this problem.
[9]:
[2*x for x in range(1,11)]
[9]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
That’s it!. Only remember to enclose it in square brackets
Understanding the code, The first bit of the code is always the algorithm and then leave a space and then write the necessary loop. But you might be wondering can nested loops be extended to list comprehensions? Yes you can.
[10]:
[2*x for x in range(1,20) if x<=10]
[10]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Let me add one more loop to make you understand better,
[11]:
[2*z for i in range(50) if i==6 for z in range(1,11)]
[11]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[ ]:
[ ]: