Python - iteration

Loops

for loop

In [70]:
list1 = [1,2,3,4,5,6,7]
for element in list1:
    print(element)
1
2
3
4
5
6
7
In [71]:
for element in list1:
    print(element, " squared ", element*element)
1  squared  1
2  squared  4
3  squared  9
4  squared  16
5  squared  25
6  squared  36
7  squared  49
In [72]:
for count in range(11,20):
    print(str(count))
11
12
13
14
15
16
17
18
19

For-else statement

The else block of the For-else is run if the for loop runs without encountering a break statement

In [19]:
# Find the multiple of 7

for i in range(1,6):
    print(i, end= " ")
    
    if i % 7 == 0:
        print(f'\nMultiple of 7 found: {i}')
        break
else:
    print('\nNo multiples of 7 found in this series')
1 2 3 4 5 
No multiples of 7 found in this series
In [ ]:
 

While loop

while <condition>:
    statements

Runs until condition becomes false.

In [5]:
a = 5
while a < 10:
    print(a)
    a += 1
5
6
7
8
9
Do While loop emulation in Python

There is no do while loop, but we can jimmy one. Do-while pattern is good in scenarios where an iterable code needs to be run at-least once.

In [6]:
a = 5

while True:  ## Do-while emulation
    print(a)
    a += 1
    if a >= 10:
        break
5
6
7
8
9
In [8]:
# Fashion a username getter that won't give up until a valid username is input.

min_char = 2

while True:
    name = input("Enter your username: ")
    if len(name) >= min_char and name.isprintable() and name.isalpha():
        break

print(f"Hello {name}")
Enter your username: ./\
Enter your username: --0
Enter your username: 90
Enter your username: atma
Hello atma
While Else loop

The While-Else offers an option where the Else block get executed if the While block did not encounter a break statement. This is useful to insert logic that needs to run if the while loop iterated to its entirity.

In [13]:
# check if an element exists and append it to a list.
l = [9,18,27]
idx = 0
val = 36

while idx < len(l):
    if l[idx] == val:
        break  # no need to append
    idx += 1

else:
    l.append(val)

print(l)
[9, 18, 27, 36]

Continue statement

Allows a loop to skip an interation when some condition is met

In [11]:
a = 4
while True:
    a += 1
    if a == 7:  # skip on condition
        print("Skipped")
        continue
    print(a)
    
    if a > 11:
        break
    
5
6
Skipped
8
9
10
11
12

Comprehensions

Comprehensions are an effective way to loop through sequences

List comprehension

   [operation for index in sequence condition] 
In [73]:
list2_comp = [e*e for e in list1]
list2_comp
Out[73]:
[1, 4, 9, 16, 25, 36, 49]
In [74]:
list2_even = [e*e for e in list1 if e%2==0]
list2_even
Out[74]:
[4, 16, 36]

Dictionary comprehension

Same as list comprehension, but instead of lists, it returns a dictionary. You use {} instead of []

{key:value for key, value in dictionary if condition}
In [39]:
d3 = {'day':'Thursday',
     'day_of_week':5,
     'start_of_week':'Sunday',
     'day_of_year':123,
     'dod':{'month_of_year':'Feb',
           'year':2017},
     'list1':[8,7,66]}
In [43]:
# get those kvp whose value is a list
{k:v for k,v in d3.items() if type(v)==list}
Out[43]:
{'list1': [8, 7, 66]}

reverse keys and values? - works only when values are immutable types. hence filter them out

In [45]:
d4 = {k:v for k,v in d3.items() if type(v) not in [list, dict]}
d4
Out[45]:
{'day': 'Thursday',
 'day_of_week': 5,
 'day_of_year': 123,
 'start_of_week': 'Sunday'}
In [47]:
# reverse keys and values
d4_reverse = {v:k for k,v in d4.items()}
d4_reverse
Out[47]:
{'Thursday': 'day',
 5: 'day_of_week',
 'Sunday': 'start_of_week',
 123: 'day_of_year'}
In [ ]: