cities = ["mumbai", "delhi", "hyderabad", "bangaluru", "chennai"]12 Module 2 - Day 1
Topics
- Iteration patterns
- list comprehensions
- Mapping one list to another list
- Filtering lists on some conditions
For today’s practice make use of notebook module2-day1.ipynb created in your enviroment. Shut down kernel for all previous notebooks (if in runing condition) by right cliking on notbeook on left hand side file browser.
12.1 Iteration Patterns
for c in cities:
print(c)mumbai
delhi
hyderabad
bangaluru
chennai
cities[0]'mumbai'
cities[1]'delhi'
cities[10]--------------------------------------------------------------------------- IndexError Traceback (most recent call last) Cell In[5], line 1 ----> 1 cities[10] IndexError: list index out of range
for i, item in enumerate(cities):
print(i, item)0 mumbai
1 delhi
2 hyderabad
3 bangaluru
4 chennai
for i, item in enumerate(cities, start=1):
print(i, item)1 mumbai
2 delhi
3 hyderabad
4 bangaluru
5 chennai
cities['mumbai', 'delhi', 'hyderabad', 'bangaluru', 'chennai']
for c in reversed(cities):
print(c)chennai
bangaluru
hyderabad
delhi
mumbai
r = reversed(cities)r<list_reverseiterator at 0x770544466200>
iterator does not have actual data. it has some way to access the original data. An iterator once created allows us to go through the data once.
next(r)'chennai'
next(r)'bangaluru'
next(r)'hyderabad'
next(r)'delhi'
next(r)'mumbai'
next(r)--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) Cell In[17], line 1 ----> 1 next(r) StopIteration:
r = reversed(cities)
for c in r: # for loop is consuming the iteartor r
print(c)chennai
bangaluru
hyderabad
delhi
mumbai
for c in reversed(cities):
print(c)chennai
bangaluru
hyderabad
delhi
mumbai
for c in r: # for loop will not find any data in r because r is alread consumed in above loop!
print(c)for c in reversed(cities):
print(c)chennai
bangaluru
hyderabad
delhi
mumbai
states = ["Maharashtra", "Delhi", "Andhra Pradesh", "Karanataka", "Tamilnadu"]cities['mumbai', 'delhi', 'hyderabad', 'bangaluru', 'chennai']
states[0], cities[0]('Maharashtra', 'mumbai')
for i in range(len(cities)):
print(states[i], cities[i]) # we are indexingMaharashtra mumbai
Delhi delhi
Andhra Pradesh hyderabad
Karanataka bangaluru
Tamilnadu chennai
for city, state in zip(cities, states):
print(city, state)mumbai Maharashtra
delhi Delhi
hyderabad Andhra Pradesh
bangaluru Karanataka
chennai Tamilnadu
x = ["x1", "x2", "x3", "x4"]
y = ["y1", "y2", "y3", "y4"]
z = ["z1", "z2", "z3", "z4", "z5"]for x_, y_, z_ in zip(x, y, z):
print(x_, y_, z_)x1 y1 z1
x2 y2 z2
x3 y3 z3
x4 y4 z4
problem
Write a function vector_add, which does vector addition of two vectors taken as lists
>>> vector_add([1, 1, 1], [3, 4, 5])
[4, 5, 6]
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)
problem There are two lists
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
write a function merge which will merge the lists into a single list such that alternatively one item from first list and one item from second list is taken. e.g for above case the merge should result in::
>>> merge(a, b)
[1, 'a', 2, 'b', 3, 'c']
def square(nums):
for n in nums:
print(n*n)square([1, 2, 3, 4, 5])1
4
9
16
25
def square(nums):
sqr = []
for n in nums:
sqr.append(n*n)square([1, 2, 3, 4, 5])def mysum(nums):
s = 0
for n in nums:
s += n
return sones = [1, 1,1 ]ones + ones[1, 1, 1, 1, 1, 1]
ones.extend([1, 2, 3])ones[1, 1, 1, 1, 2, 3]
def vector_add(vector1, vector2):
addition = []
for v1, v2 in zip(vector1, vector2):
addition.append(v1+ v2)
return additionvector_add([1, 1, 1], [1, 2, 3])[2, 3, 4]
x1 = [12123, 34323, 4545, 67000]
x2 = [100000, 23000, 23233, 3445]
x3 = [42344, 45000, 12000, 20000]x1x2 = vector_add(x1, x2)vector_add(x1x2, x3)[154467, 102323, 39778, 90445]
def merge(collection1, collection2):
merged = []
for c1, c2 in zip(collection1, collection2):
merged.extend([c1, c2])
return mergedmerge([1, 2, 3], ['a','b','c'])[1, 'a', 2, 'b', 3, 'c']
12.1.1 function with variable number of arguments
max(1, 2, 3, 4)4
max([1, 2, 3, 4])4
max(1, 2)2
zip(x, y)<zip at 0x770544917480>
zip(x, y, z)<zip at 0x770544cc9a40>
for a,b in zip(x,y):
print(a, b)x1 y1
x2 y2
x3 y3
x4 y4
for item in zip(x, y):
print(item)('x1', 'y1')
('x2', 'y2')
('x3', 'y3')
('x4', 'y4')
def add(a, b):
return a+badd(1, 2)3
two = [23, 45]add(two[0], two[1])68
add(*two) # each item from list two will be passed as separate argument to add68
def vector_add(*args): # here args will come as tuple which can have any size
#that user passes while callling the function
addition = []
for item in zip(*args):
addition.append(sum(item))
return additionvector_add(x1, x2)[112123, 57323, 27778, 70445]
vector_add(x1, x2, x3)[154467, 102323, 39778, 90445]
max(1, 2)2
max(1, 2, 3, 5)5
def mysum(*args):
s = 0
for i in args:
s = s + i
return smysum(1, 2)3
mysum(1, 2, 3, 4, 5)15
add(1, 2, 3)--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[80], line 1 ----> 1 add(1, 2, 3) TypeError: add() takes 2 positional arguments but 3 were given
12.2 List Comprehension
empty = []
for c in cities:
empty.append(c.upper())empty['MUMBAI', 'DELHI', 'HYDERABAD', 'BANGALURU', 'CHENNAI']
cities['mumbai', 'delhi', 'hyderabad', 'bangaluru', 'chennai']
nums = [1, 2, 3, 4, 5, 6]sqr = []
for n in nums:
sqr.append(n*n)sqr[1, 4, 9, 16, 25, 36]
def f(x):
return x**2 + 2*x + 1func_values = []
for n in nums:
func_values.append(f(n))func_values[4, 9, 16, 25, 36, 49]
[n*n for n in nums][1, 4, 9, 16, 25, 36]
[n**3 for n in nums][1, 8, 27, 64, 125, 216]
[f(n) for n in nums][4, 9, 16, 25, 36, 49]
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]evens = []
for n in nums:
if n%2==0:
evens.append(n)evens[2, 4, 6, 8, 10]
[n for n in nums if n%2==0][2, 4, 6, 8, 10]
[n for n in nums if n%2==1][1, 3, 5, 7, 9]
newitem = []
for item in olditems:
newitem.append(do_something(item))
newitems = [do_something(item) for item in olditems]
def findlens(words):
lens = []
for word in words:
lens.append(len(word))
return lenswords = "hello give me some words please".split()findlens(words)[5, 4, 2, 4, 5, 6]
[len(w) for w in words][5, 4, 2, 4, 5, 6]
import datetimedates = []
start = datetime.datetime.today()
for i in range(5):
nextday = start + datetime.timedelta(days=i)
dates.append(nextday)
datesimport datetime
def trange(n):
"""
generates next n dates starting from today
"""
dates = []
start = datetime.datetime.today()
for i in range(n):
dates.append(start + datetime.timedelta(days=i))[datetime.datetime(2026, 1, 12, 7, 16, 11, 760920),
datetime.datetime(2026, 1, 13, 7, 16, 11, 760920),
datetime.datetime(2026, 1, 14, 7, 16, 11, 760920),
datetime.datetime(2026, 1, 15, 7, 16, 11, 760920),
datetime.datetime(2026, 1, 16, 7, 16, 11, 760920)]
today = datetime.datetime.today()
[today + datetime.timedelta(days=i) for i in range(5)][datetime.datetime(2026, 1, 12, 7, 17, 15, 838632),
datetime.datetime(2026, 1, 13, 7, 17, 15, 838632),
datetime.datetime(2026, 1, 14, 7, 17, 15, 838632),
datetime.datetime(2026, 1, 15, 7, 17, 15, 838632),
datetime.datetime(2026, 1, 16, 7, 17, 15, 838632)]
todaydatetime.datetime(2026, 1, 12, 7, 17, 15, 838632)
today + datetime.timedelta(days=10)datetime.datetime(2026, 1, 22, 7, 17, 15, 838632)
datetime.datetime.today<function datetime.today>
datetime.datetime.today()datetime.datetime(2026, 1, 12, 7, 41, 24, 204272)
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)]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)
for ticker, day, value in indexdata:
print(ticker, day, value)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
[ value for ticker, day, value in indexdata if day=="Monday"][111.71436961893693, 235.0403622499107, 321.49182055844256]
[ (ticker,value) for ticker, day, value in indexdata if day=="Monday"][('IBM', 111.71436961893693),
('MICROSOFT', 235.0403622499107),
('APPLE', 321.49182055844256)]
12.3 Dictinary Comprehension
[ (ticker,value) for ticker, day, value in indexdata if day=="Monday"][('IBM', 111.71436961893693),
('MICROSOFT', 235.0403622499107),
('APPLE', 321.49182055844256)]
{ticker:value for ticker, day, value in indexdata}{'IBM': 140.25154281801224,
'MICROSOFT': 235.80850482793264,
'APPLE': 318.3912296144338}
monday_values = {ticker:value for ticker, day, value in indexdata}monday_values['APPLE']318.3912296144338
{day:value for ticker, day, value in indexdata if ticker=="APPLE"}{'Monday': 321.49182055844256,
'Tuesday': 340.63612771662815,
'Wednesday': 303.9065277507285,
'Thursday': 338.1350605764038,
'Friday': 318.3912296144338}
def filter_by_ticker(tickername, indexdata):
return {day:value for ticker, day, value in indexdata}filter_by_ticker("IBM", indexdata){'Monday': 321.49182055844256,
'Tuesday': 340.63612771662815,
'Wednesday': 303.9065277507285,
'Thursday': 338.1350605764038,
'Friday': 318.3912296144338}
filter_by_ticker("APPLE", indexdata){'Monday': 321.49182055844256,
'Tuesday': 340.63612771662815,
'Wednesday': 303.9065277507285,
'Thursday': 338.1350605764038,
'Friday': 318.3912296144338}
def filter_by_day(day_, indexdata):
return {ticker:value for ticker, day, value in indexdata if day==day_}filter_by_day("Monday", indexdata){'IBM': 111.71436961893693,
'MICROSOFT': 235.0403622499107,
'APPLE': 321.49182055844256}
12.3.1 problems
import osos.listdir()['hello.py',
'index.qmd',
'addnums.py',
'txt1.txt',
'module1-day5.ipynb',
'__pycache__',
'stats2.py',
'addnumbers.py',
'test',
'test1',
'box.py',
'addition.py',
'countdown.py',
'stats1.py',
'printwords.py',
'.ipynb_checkpoints',
'printwords,py',
'square.py',
'voice_of_wild.py',
'cat1.py',
'module2-day1.ipynb',
'module1-day4.ipynb',
'module1-day1.ipynb',
'args.py',
'module1-day3.ipynb',
'cube.py',
'cat.py',
'stats.py',
'module1-day2.ipynb',
'add.py',
'hello.txt',
'untitled.py',
'nurturing-session1.ipynb']
os.getcwd()'/opt/arcesium-finop-25/website/live-notes'
os.listdir(os.getcwd())['hello.py',
'index.qmd',
'addnums.py',
'txt1.txt',
'module1-day5.ipynb',
'__pycache__',
'stats2.py',
'addnumbers.py',
'test',
'test1',
'box.py',
'addition.py',
'countdown.py',
'stats1.py',
'printwords.py',
'.ipynb_checkpoints',
'printwords,py',
'square.py',
'voice_of_wild.py',
'cat1.py',
'module2-day1.ipynb',
'module1-day4.ipynb',
'module1-day1.ipynb',
'args.py',
'module1-day3.ipynb',
'cube.py',
'cat.py',
'stats.py',
'module1-day2.ipynb',
'add.py',
'hello.txt',
'untitled.py',
'nurturing-session1.ipynb']
files = os.listdir()[f for f in files if f.endswith("ipynb"]Cell In[134], line 1 [f for f in files if f.endswith("ipynb"] ^ SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
[f for f in files if f.endswith("ipynb")]['module1-day5.ipynb',
'module2-day1.ipynb',
'module1-day4.ipynb',
'module1-day1.ipynb',
'module1-day3.ipynb',
'module1-day2.ipynb',
'nurturing-session1.ipynb']
import os
def filterfiles(folder, extension):
files = os.listdir(folder)
return [f for f in files if f.endswith(extension)]filterfiles(os.getcwd(), ".py")['hello.py',
'addnums.py',
'stats2.py',
'addnumbers.py',
'box.py',
'addition.py',
'countdown.py',
'stats1.py',
'printwords.py',
'square.py',
'voice_of_wild.py',
'cat1.py',
'args.py',
'cube.py',
'cat.py',
'stats.py',
'add.py',
'untitled.py']
Problems - find sum of all multiples of 7 or 11 below 1000.
There is a string “abrakadabra”, we want to capitalize alternate character from it. how can we do it? can a list comprehension be used to do this?
Write a function factors which finds all factors of given number (include 1 and self)
Write a function is_prime which checks if given number is prime based on fact that prime number has only two factors 1 and self.
Write a list comprehension to generate prime numbers.
sum([n for n in range(1000) if n%7==0 or n%11==0])110110
text = "abrakadabra"text[::2] # we got all chars starting from first till end and alternate position'arkdba'
text[1::2]'baaar'
text[1::2].upper()'BAAAR'
merge()--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[147], line 1 ----> 1 merge() TypeError: merge() missing 2 required positional arguments: 'collection1' and 'collection2'
"".join(merge(text[::2], text[1::2].upper())) 'aBrAkAdAbR'
text1 = text[::2]
text2 = text[1::2].upper()"".join([x+y for x, y in zip(text1, text2)]) + text1[-1]'aBrAkAdAbRa'
def factors(n):
return [f for f in range(1, n+1) if n%f==0]factors(10)[1, 2, 5, 10]
factors(5)[1, 5]
def is_prime(n):
return factors(n) == [1, n]is_prime(13)True
is_prime(12)False
[p for p in range(100) if is_prime(p)][2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97]
12.4 Reading files
%%file poem.txt
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!Writing poem.txt
with open("poem.txt") as f:
contents = f.read()contents"The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n"
with open("poem.txt") as f:
print(f.readline()) # will read only one lineThe Zen of Python, by Tim Peters
f = open("poem.txt")f.readline() # this will read first line'The Zen of Python, by Tim Peters\n'
f.readline() # this will next line'\n'
f.readline()'Beautiful is better than ugly.\n'
for line in f:
print(line)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!
f.readline()''
f.close()with open("poem.txt") as f:
for line in f:
print(line, end="")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!