2. Page | 1
Contents
I. #importing…………………………………………………………………………………………………..2
II. #str……………………………………………………………………………………………………….3
III. #bytes……………………………………………………………………………………………………7
IV. #for-loop………………………………………………………………………………………………8
V. #list………………………………………………………………………………………………………9
VI. #tuple…………………………………………………………………………………………………..15
VII. #dict…………………………………………………………………………………………………….18
VIII. #range………………………………………………………………………………………………..23
IX. #set…………………………………………………………………………………………………….25
X. #Collection protocols………………………………………………………………………..28
XI. #Comprehensions……………………………………………………………………………..29
XII. #Generators……………………………………………………………………………………….31
3. Page | 2
#importing
Import modules
import math
s=math.sqrt(8)
print(s)
2.8284271247461903
from math import factorial
n=5
k=3
s=factorial(n)/(factorial(k)*factorial(n-k))
print(s)
10.0
from math import factorial as fac
n=5
k=3
s=fac(n)/(fac(k)*fac(n-k))
print(s)
10.0
# // use for integer division
4. Page | 3
#str
Immutable sequence of Unicode code points
#can use both ‘_’ and “_”
'This is a string'
"This is also string"
s="first""Second"
print(s)
firstSecond
#’’’_’’’ for multiline
‘’’Multi line
string
:D ‘’’
#universal newline n
print("This is nnew line")
This is
new line
#escape sequence
print("This is " in a string")
This is " in a string
#row string
path=r"C:UsersExamDocdir"
print(path)
C:UsersExamDocdir
5. Page | 4
#call by index
s="Parrot"
print(s[4])
o
#length of string
s="Beautiful is better than ugly.Explicit is better than implicit."
print(len(s))
63
#concatenates
w="new"+"found"+"land"
print(w)
newfoundland
r="new"
r+="found"
r+="land"
print(r)
newfoundland
#join
color=';'.join(["#ff2","#a34","#3542"])
print(color)
#ff2;#a34;#3542
6. Page | 5
#splitting and joining
print(color.split(';'))
['#ff2', '#a34', '#3542']
print(''.join(["high","way","man"]))
highwayman
#partition
x="unforgetable"
print(x.partition("forget"))
('un', 'forget', 'able')
#dummy variable '_'
origin,_,destination="Seattle-Boston".partition("-")
print(origin,destination)
Seattle Boston
#format
q="My name is {0}.I like {1}".format("Sumudu","Apple")
print(q)
My name is Sumudu.I like Apple
p="This {} can {} do this way.".format('method','also')
print(p)
This method can also do this way.
7. Page | 6
y="My name is {Name}.I am {Age} years
old.".format(Name="Sumudu",Age="22")
print(y)
My name is Sumudu.I am 22 years old.
pos=(34,23.6,67)
q="galactic position x={pos[0]},y={pos[2]},z={pos[1]}".format(pos=pos)
print(q)
galactic position x=34,y=67,z=23.6
import math
s="Math constants: pi={m.pi} e={m.e}".format(m=math)
print(s)
Math constants: pi=3.141592653589793 e=2.718281828459045
#get up to 3 floating point values
s="Math constants: pi={m.pi:.3f} e={m.e:.3f}".format(m=math)
print(s)
Math constants: pi=3.142 e=2.718
8. Page | 7
#bytes
Immutable sequence of bytes
#declare bytes
d=b'Some bytes'
print(d.split())
[b'Some', b'bytes']
#encoding and decoding
#using in data streaming through the networks
data="I love my girlfriend".encode('utf-8')
dc=data.decode('utf-8')
print(data)
print(dc)
b'I love my girlfriend'
I love my girlfriend
9. Page | 8
#for loop
for ITEM in SEQUENCE
cities=["Matara","Ambalangoda","Colombo","Gampaha","Halawatha"]
for city in cities:
print(city)
Matara
Ambalangoda
Colombo
Gampaha
Halawatha
color={"Red":43,"Yellow":23,"Blue":45,"Green":22}
for clr in color:
print(clr,color[clr])
Green 22
Yellow 23
Red 43
Blue 45
10. Page | 9
#list
Mutable sequence of objects
a=["apple","orange","pears"]
print(a[2])
pears
a[2]=7
print(a)
['apple', 'orange', 7]
#add items
b=[]
b.append(1.345)
b.append(1.534)
#adding element to the end of the list
s=list("This is a list")
print(s)
['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 'l', 'i', 's', 't']
#use last comma
11. Page | 10
#negative indexing
#last element at -1
l="show how to index into sequence".split()
print(l)
print(l[-3],l[-1])
['show', 'how', 'to', 'index', 'into', 'sequence']
index sequence
#slice
#slice=seq[start:stop]
print(l[1:3])
print(l[3:])
print(l[:3])
print(l[:])
['how', 'to']
['index', 'into', 'sequence']
['show', 'how', 'to']
['show', 'how', 'to', 'index', 'into', 'sequence']
#copying
#copies are shallow
print(l[:])
print(l.copy())
print(list(l))
['show', 'how', 'to', 'index', 'into', 'sequence']
['show', 'how', 'to', 'index', 'into', 'sequence']
['show', 'how', 'to', 'index', 'into', 'sequence']
12. Page | 11
#repeat
q=l*3
print(q)
['show', 'how', 'to', 'index', 'into', 'sequence', 'show', 'how', 'to', 'index', 'into', 'sequence',
'show', 'how', 'to', 'index', 'into', 'sequence']
#index()
w="Sumudu is a good girl.Sumudu is beautiful".split()
i=w.index('good')
print(i)
3
#count()
print(w.count('is'))
2
#membership
print('Sumudu' in w)
print('love' not in w)
True
True
#delete
u="Jack is a woodcutter".split()
del u[3]
print(u)
['Jack', 'is', 'a']
13. Page | 12
#raise value error if value is not in list
u.remove('Jack')
#insert
u.insert(0,'Sumudu')
u.insert(3,'girl')
print(u)
['Sumudu', 'is', 'a', 'girl']
#concatenate
m=[1,3,5,7,9]
n=[2,4,6,8,10]
k=m+n
print(k)
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
k+=[20,30,40]
print(k)
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10, 20, 30, 40]
k.extend([90,100])
print(k)
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10, 20, 30, 40, 90, 100]
14. Page | 13
#reverse
g=[1,2,3,4,5]
g.reverse()
print(g)
[5, 4, 3, 2, 1]
#sort
h=[4,7,2,1,5,9,8]
h.sort()
print(h)
[1, 2, 4, 5, 7, 8, 9]
h.sort(reverse=True)
print(h)
[9, 8, 7, 5, 4, 2, 1]
h="Moon is so beautiful when you are with me".split()
h.sort(key=len)
print(h)
['is', 'so', 'me', 'you', 'are', 'Moon', 'when', 'with', 'beautiful']
#join
print(' '.join(h))
is so me you are Moon when with beautiful
#empty
e=[]
15. Page | 14
#sorted
#not change the original list
x=[10,2,3,5,8,7]
y=sorted(x)
print(x,y)
[10, 2, 3, 5, 8, 7] [2, 3, 5, 7, 8, 10]
#reversed
p=[8,7,6,5,4,3]
q=reversed(p)
print(q)
print(list(q))
<list_reverseiterator object at 0x03CEFFB0>
[3, 4, 5, 6, 7, 8]
21. Page | 20
#values
for value in d.values():
print(value)
25
22
21
24
34
#no efficient way to get key from value
for key in d.keys():
print(key)
Manusha
Sumudu
Nimal
Thilina
Bob
#items give both key and values
for key,val in d.items():
print("{key} => {val}".format(key=key,val=val))
Manusha => 25
Sumudu => 22
Nimal => 21
Thilina => 24
Bob => 34
30. Page | 29
#Comprehensions
[expr(item) for item in iterable]
#list comprehensions
words="This is a sample word list to experiment".split()
x=[len(word) for word in words]
print(x)
[4, 2, 1, 6, 4, 4, 2, 10]
from math import factorial
f=[len(str(factorial(x))) for x in range(20)]
print(f)
[1, 1, 1, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 18]
#set comprehensions
r={len(str(factorial(x))) for x in range(20)}
print(r)
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 18}
#dict comprehensions
from pprint import pprint as pp
c_c={'Sumudu':22,"Manusha":25,"Bob":23}
p={age:name for name,age in c_c.items()}
pp(p)
{22: 'Sumudu', 23: 'Bob', 25: 'Manusha'}
31. Page | 30
#filtering predicates
from math import sqrt
def is_prime(x):
if x <2:
return False
for i in range(2,int(sqrt(x))+1):
if x%i==0:
return False
return True
print([x for x in range(101) if is_prime(x)])
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49,
51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93,
95, 97, 99]
#iteration protocols
#end of list StopIteration error
iterable=['Spring','Summer','Autumn','Winter']
iterator=iter(iterable)
print(next(iterator))
print(next(iterator))
Spring
Summer
32. Page | 31
#Generators
#create independent generators
def gen123():
yield 1
yield 2
yield 3
g=gen123()
print(next(g))
1
for v in g:
print(v)
1
2
3
#generator comprehensions
million_squares=(x*x for x in range(1,100001))
print(million_squares)
<generator object <genexpr> at 0x041911E8>
33. Page | 32
#print(list(million_squares))
#generators are single used objects
print(sum(x*x for x in range(1,100001)))
print(sum(x for x in range(10001)if is_prime(x)))
333338333350000
24999996
#itertools
from itertools import islice,count
tp=islice((x for x in count() if is_prime(x)),1000)
print(sum(tp))
1004000
#any / all
print(any([False,False,True]))
print(all([False,True,True]))
print(any(is_prime(x) for x in range(1328,2001)))
True
False
True
34. Page | 33
#zip
sun=[12,14,11,15,11]
mon=[1,4,5,6,3]
for item in zip(sun,mon):
print(item)
(12, 1)
(14, 4)
(11, 5)
(15, 6)
(11, 3)
for s,m in zip(sun,mon):
print("Average= ",(s+m)/2)
Average= 6.5
Average= 9.0
Average= 8.0
Average= 10.5
Average= 7.0
#chain
from itertools import chain
temp=chain(sun,mon)
print(all(t>0 for t in temp))
True