Module 2 - Day 1

Iteration Patterns - enumerate

e = []
for i in range(5): # given list
    e.append(i**2)
e
[0, 1, 4, 9, 16]
e1 = []
for i in range(5): # given list
    if i%2 == 0:
        e1.append(i**2)
e1
[0, 4, 16]
students = ["Akanksha", "Akash", "Aksh", "Arvind", "Amogh", "Anshul"]
for student in students:
    print(student)
Akanksha
Akash
Aksh
Arvind
Amogh
Anshul
i = 0 
for student in students:
    print(i, student)
    i = i + 1 # increament i
0 Akanksha
1 Akash
2 Aksh
3 Arvind
4 Amogh
5 Anshul
for i, student in enumerate(students):
    print(i, student)
0 Akanksha
1 Akash
2 Aksh
3 Arvind
4 Amogh
5 Anshul
poem = """The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
lines = poem.split("\n") # \n new line char, split will divide the string 
                        # into list of multiple strings 
lines
['The Zen of Python, by Tim Peters',
 '',
 'Beautiful is better than ugly.',
 'Explicit is better than implicit.',
 'Simple is better than complex.',
 'Complex is better than complicated.',
 'Flat is better than nested.',
 'Sparse is better than dense.',
 'Readability counts.',
 "Special cases aren't special enough to break the rules.",
 'Although practicality beats purity.',
 'Errors should never pass silently.',
 'Unless explicitly silenced.',
 'In the face of ambiguity, refuse the temptation to guess.',
 'There should be one-- and preferably only one --obvious way to do it.',
 "Although that way may not be obvious at first unless you're Dutch.",
 'Now is better than never.',
 'Although never is often better than *right* now.',
 "If the implementation is hard to explain, it's a bad idea.",
 'If the implementation is easy to explain, it may be a good idea.',
 "Namespaces are one honking great idea -- let's do more of those!"]
words = ["one", "two", "three", "four"]
words
['one', 'two', 'three', 'four']
words[0] #[index]
'one'
words[1]
'two'
words[2]
'three'
words = ["zero", "one", "two", "three", "four"]
words[0]
'zero'
for w in words:
    print(w)
zero
one
two
three
four
index = 0
for w in words:
    print(index, w)
    index = index + 1
0 zero
1 one
2 two
3 three
4 four
list(enumerate(words))
[(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
for i, value in enumerate(words):
    print(i, value)
0 zero
1 one
2 two
3 three
4 four
sentence = "Life is difficult as well as simple"
for c in sentence:
    print(c)
L
i
f
e
 
i
s
 
d
i
f
f
i
c
u
l
t
 
a
s
 
w
e
l
l
 
a
s
 
s
i
m
p
l
e
for pos, c in enumerate(sentence):
    print(pos, c)
0 L
1 i
2 f
3 e
4  
5 i
6 s
7  
8 d
9 i
10 f
11 f
12 i
13 c
14 u
15 l
16 t
17  
18 a
19 s
20  
21 w
22 e
23 l
24 l
25  
26 a
27 s
28  
29 s
30 i
31 m
32 p
33 l
34 e
for i, j in enumerate(range(10)):
    print(i, j)
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
different_nums = ["two", "three", "four", "five"]
for i, n in enumerate(different_nums, start=2):
    print(i, n)
2 two
3 three
4 four
5 five

problem

  • Take lines from poem “zen of python” and print the poem with line numbers
enumerate(lines)
<enumerate at 0x734f1010c740>
range(10)
range(0, 10)
for i, line in enumerate(lines, start=1):
    print(i, line)
1 The Zen of Python, by Tim Peters
2 
3 Beautiful is better than ugly.
4 Explicit is better than implicit.
5 Simple is better than complex.
6 Complex is better than complicated.
7 Flat is better than nested.
8 Sparse is better than dense.
9 Readability counts.
10 Special cases aren't special enough to break the rules.
11 Although practicality beats purity.
12 Errors should never pass silently.
13 Unless explicitly silenced.
14 In the face of ambiguity, refuse the temptation to guess.
15 There should be one-- and preferably only one --obvious way to do it.
16 Although that way may not be obvious at first unless you're Dutch.
17 Now is better than never.
18 Although never is often better than *right* now.
19 If the implementation is hard to explain, it's a bad idea.
20 If the implementation is easy to explain, it may be a good idea.
21 Namespaces are one honking great idea -- let's do more of those!

zip

firstname = ["Alice", "Elsa", "Alex", "Elisa"]
lastname = ["Wondergirl", "Frozen", "Lion", "Hacker"]
n = len(firstname)
for i in range(n):
    print(firstname[i], lastname[i]) # key point is finding ith item from both the list
Alice Wondergirl
Elsa Frozen
Alex Lion
Elisa Hacker
for first,last in zip(firstname, lastname):
    print(first, last)
Alice Wondergirl
Elsa Frozen
Alex Lion
Elisa Hacker
xs = ["x1", "x2", "x3", "x4"]
ys = ["y1", "y2", "y3", "y4"]
zs = ["z1", "z2", "z3", "z4"]

for x,y,z in zip(xs, ys, zs):
    print(x, y, z)
x1 y1 z1
x2 y2 z2
x3 y3 z3
x4 y4 z4
tickers = ["IBM", "APPLE", "AGILENT", "MICOSOFT"]
values = [123.5, 125.7, 223.6, 212]
for ticker, value in zip(tickers, values):
    print(ticker, value)
IBM 123.5
APPLE 125.7
AGILENT 223.6
MICOSOFT 212
data = {}
for t, v in zip(tickers, values):
    data[t] = v
data
{'IBM': 123.5, 'APPLE': 125.7, 'AGILENT': 223.6, 'MICOSOFT': 212}
data['IBM']
123.5
datalist = []
for t, v in zip(tickers, values):
    datalist.append([t,v])
datalist
[['IBM', 123.5], ['APPLE', 125.7], ['AGILENT', 223.6], ['MICOSOFT', 212]]
datalist = []
for t, v in zip(tickers, values):
    datalist.append((t, v))
datalist
[('IBM', 123.5), ('APPLE', 125.7), ('AGILENT', 223.6), ('MICOSOFT', 212)]
d = {}
d['name'] = "Vikrant" # to add item in dictionary make use of square brackets
d
{'name': 'Vikrant'}
d("name")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[57], line 1
----> 1 d("name")

TypeError: 'dict' object is not callable
x  = [1, 2, 3, 4, 5, 6]
y = [1, 4, 9, 16]
for i, j in zip(x, y): # will loop over only smallest list
    print(i, j)
1 1
2 4
3 9
4 16

reverse

students
['Akanksha', 'Akash', 'Aksh', 'Arvind', 'Amogh', 'Anshul']
for s in reversed(students):
    print(s)
Anshul
Amogh
Arvind
Aksh
Akash
Akanksha
for i in range(5):
    print(i)
0
1
2
3
4
for i in reversed(range(5)):
    print(i)
4
3
2
1
0
for line in reversed(lines):
    print(line)
Namespaces are one honking great idea -- let's do more of those!
If the implementation is easy to explain, it may be a good idea.
If the implementation is hard to explain, it's a bad idea.
Although never is often better than *right* now.
Now is better than never.
Although that way may not be obvious at first unless you're Dutch.
There should be one-- and preferably only one --obvious way to do it.
In the face of ambiguity, refuse the temptation to guess.
Unless explicitly silenced.
Errors should never pass silently.
Although practicality beats purity.
Special cases aren't special enough to break the rules.
Readability counts.
Sparse is better than dense.
Flat is better than nested.
Complex is better than complicated.
Simple is better than complex.
Explicit is better than implicit.
Beautiful is better than ugly.

The Zen of Python, by Tim Peters
words
['zero', 'one', 'two', 'three', 'four']
for w in reversed(words):
    print(w)
four
three
two
one
zero
def countfdown(n):
    for i in reversed(range(n)):
        print(i)
        
countfdown(5)
4
3
2
1
0

problem

Original data is given in tabular format

name , salary, business, stocks, house property, 
x1, 12123, 34323, 4545, 67000
x2, 100000, 23000, 23233, 3445
x3, 42344, 45000, 12000, 20000

given to you in list format

x1 = [12123, 34323, 4545, 67000]
x2 = [100000, 23000, 23233, 3445]
x3 = [42344, 45000, 12000, 20000]

find total of every head (salary, business, stocks, porperty)

x1 = [12123, 34323, 4545, 67000]
x2 = [100000, 23000, 23233, 3445]
x3 = [42344, 45000, 12000, 20000]
x1 + x2 
[12123, 34323, 4545, 67000, 100000, 23000, 23233, 3445]
for i, j in zip(x1, x2):
    print(i + j)
112123
57323
27778
70445
heads = ["salary", "business", "stocks", "house property"] 
for h, i,j,k in zip(heads, x1, x2, x3):
    print(h, i+j+k)
salary 154467
business 102323
stocks 39778
house property 90445

Behaviour of an iterator

r = reversed(words) # lets save it into a variable
r # it does not show values, but it shows what is this object
<list_reverseiterator at 0x734f0620b940>
for w in r:
    print(w)
four
three
two
one
zero
for w in r: # this will result into empty loop
    print(w)
e = enumerate(words)
for i, w in e:
    print(i, w)
0 zero
1 one
2 two
3 three
4 four
for i, w in e:
    print(i, w)
names = zip(firstname, lastname)
for f,l in names:
    print(f, l)
Alice Wondergirl
Elsa Frozen
Alex Lion
Elisa Hacker
for f,l in names:
    print(f, l)
rw = list(reversed(words))
rw
['four', 'three', 'two', 'one', 'zero']
rw
['four', 'three', 'two', 'one', 'zero']

List comprehensions

e = []
for i in range(5): # given list
    e.append(i**2)
caps = []
for w in words:
    caps.append(w.upper())
caps
['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR']
e = []
for i in range(5): # given list
    e.append(i**3)
empty = []
for item in existing_list:
    empty.append(do_some_operation(item))
[ do_some_operation(item) for item in existing_list]
e = []
for i in range(5): # given list
    e.append(i**2)
e
[0, 1, 4, 9, 16]
[ i**2 for i in range(5)]
[0, 1, 4, 9, 16]
[w.upper() for w in words]
['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR']

problem - Write a list comprehension to find out lengths of words given list of words

words
['zero', 'one', 'two', 'three', 'four']
lens = [] 
for w in words:
    lens.append(len(w))
lens
[4, 3, 3, 5, 4]
[len(w) for w in words]
[4, 3, 3, 5, 4]

Filtering based on conditions

e = []
for i in range(10):
    if i%2==0:
        e.append(i**2)
e
[0, 4, 16, 36, 64]
words_oflen3 = []
for w in words:
    if len(w) == 3:
        words_oflen3.append(w)
words_oflen3
['one', 'two']
[i**2 for i in range(10) if i%2==0]
[0, 4, 16, 36, 64]
[w for w in words if len (w) == 3]
['one', 'two']
stock_prices = [2000, 1500, 2300, 1700, 1200]
[p for p in stock_prices if p >=2000]
[2000, 2300]
[w for w in words if len (w) == 3 and w.startswith("o")]
['one']
[w for w in words if len (w) == 3 and (w.startswith("o") or w.endswith("o"))]
['one', 'two']

Example - indexdata

indexdata = [('IBM', 'Monday', 111.71436961893693),
            ('IBM', 'Tuesday', 141.21220022208635),
            ('IBM', 'Wednesday', 112.40571010053796),
            ('IBM', 'Thursday', 137.54133351926248),
            ('IBM', 'Friday', 140.25154281801224),
            ('MICROSOFT', 'Monday', 235.0403622499107),
            ('MICROSOFT', 'Tuesday', 225.0206535036475),
            ('MICROSOFT', 'Wednesday', 216.10342426936444),
            ('MICROSOFT', 'Thursday', 200.38038844494193),
            ('MICROSOFT', 'Friday', 235.80850482793264),
            ('APPLE', 'Monday', 321.49182055844256),
            ('APPLE', 'Tuesday', 340.63612771662815),
            ('APPLE', 'Wednesday', 303.9065277507285),
            ('APPLE', 'Thursday', 338.1350605764038),
            ('APPLE', 'Friday', 318.3912296144338)]
indexdata[0]
('IBM', 'Monday', 111.71436961893693)
indexdata[0][0]
'IBM'
indexdata[0][1]
'Monday'
indexdata[0][2]
111.71436961893693
for item in indexdata:
    print(item)
('IBM', 'Monday', 111.71436961893693)
('IBM', 'Tuesday', 141.21220022208635)
('IBM', 'Wednesday', 112.40571010053796)
('IBM', 'Thursday', 137.54133351926248)
('IBM', 'Friday', 140.25154281801224)
('MICROSOFT', 'Monday', 235.0403622499107)
('MICROSOFT', 'Tuesday', 225.0206535036475)
('MICROSOFT', 'Wednesday', 216.10342426936444)
('MICROSOFT', 'Thursday', 200.38038844494193)
('MICROSOFT', 'Friday', 235.80850482793264)
('APPLE', 'Monday', 321.49182055844256)
('APPLE', 'Tuesday', 340.63612771662815)
('APPLE', 'Wednesday', 303.9065277507285)
('APPLE', 'Thursday', 338.1350605764038)
('APPLE', 'Friday', 318.3912296144338)
ibmdata = []
for item in indexdata:
    if item[0] == "IBM":
        ibmdata.append(item)
ibmdata
[('IBM', 'Monday', 111.71436961893693),
 ('IBM', 'Tuesday', 141.21220022208635),
 ('IBM', 'Wednesday', 112.40571010053796),
 ('IBM', 'Thursday', 137.54133351926248),
 ('IBM', 'Friday', 140.25154281801224)]
[item for item in indexdata if item[0]=="IBM"]
[('IBM', 'Monday', 111.71436961893693),
 ('IBM', 'Tuesday', 141.21220022208635),
 ('IBM', 'Wednesday', 112.40571010053796),
 ('IBM', 'Thursday', 137.54133351926248),
 ('IBM', 'Friday', 140.25154281801224)]
[(name, day, price) for name, day, price in indexdata if name=="IBM"]
[('IBM', 'Monday', 111.71436961893693),
 ('IBM', 'Tuesday', 141.21220022208635),
 ('IBM', 'Wednesday', 112.40571010053796),
 ('IBM', 'Thursday', 137.54133351926248),
 ('IBM', 'Friday', 140.25154281801224)]

problem write a function get_prices which finds prices for given symbol

get_prices("IBM", indexdata)
[111.71436961893693,141.21220022208635,112.40571010053796,137.54133351926248,140.25154281801224]
[item for item in indexdata if item[0]=="IBM"] # here item is a tuple
[('IBM', 'Monday', 111.71436961893693),
 ('IBM', 'Tuesday', 141.21220022208635),
 ('IBM', 'Wednesday', 112.40571010053796),
 ('IBM', 'Thursday', 137.54133351926248),
 ('IBM', 'Friday', 140.25154281801224)]
[(name, day, price) for name, day, price in indexdata if name=="IBM"]
[('IBM', 'Monday', 111.71436961893693),
 ('IBM', 'Tuesday', 141.21220022208635),
 ('IBM', 'Wednesday', 112.40571010053796),
 ('IBM', 'Thursday', 137.54133351926248),
 ('IBM', 'Friday', 140.25154281801224)]
[price for name, day, price in indexdata if name=="IBM"]
[111.71436961893693,
 141.21220022208635,
 112.40571010053796,
 137.54133351926248,
 140.25154281801224]
def get_prices(symbol, data):
    return [price for name, day, price in data if name==symbol]
get_prices("IBM", indexdata)
[111.71436961893693,
 141.21220022208635,
 112.40571010053796,
 137.54133351926248,
 140.25154281801224]
get_prices("APPLE", indexdata)
[321.49182055844256,
 340.63612771662815,
 303.9065277507285,
 338.1350605764038,
 318.3912296144338]

problems

  • Write a list comprehension for finding data for given day (Monday)
  • Write a function to find weekly maximum for given symbol