SlideShare a Scribd company logo
#Python Collections
P.D.ManushaDilan
manushadilan@gmail.com
2015-August-15
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
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
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
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
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.
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
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
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
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
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']
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']
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]
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=[]
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]
Page | 15
#tuple
Heterogeneous immutable sequence
t=("This","Is",23,43.5)
print(t[3])
43.5
print(len(t))
4
print(t)
('This', 'Is', 23, 43.5)
for item in t:
print(item)
This
Is
23
43.5
#concatenate
print(t+("new",66))
('This', 'Is', 23, 43.5, 'new', 66)
#repeat
print(t*3)
print(type(t))
('This', 'Is', 23, 43.5, 'This', 'Is', 23, 43.5, 'This', 'Is', 23, 43.5)
<class 'tuple'>
Page | 16
#nested tuple
a=((1,2),(1,3))
print(a[1])
print(a[1][0])
(1, 3)
1
#single tuple by adding trailing comma
k=(99,)
#empty tuple
e=()
#sequence take as tuple
p=1,2,3,4,5,4
print(p)
(1, 2, 3, 4, 5, 4)
#tuple are useful for multiple return values
def minmax(item):
return min(item),max(item)
print(minmax([1,3,45,3,4,2,22]))
(1, 45)
Page | 17
#tuple unpacking
lower,upper=minmax([3,2,11,4,5,7,8,44,0])
print(lower)
print(upper)
0
44
#tuple unpacking works with nested tuples
(a,(b,(c,d)))=(4,(6,(3,5)))
print(b)
6
#idiomitic python swap
#a,b=b,a
#converting to tuple
print(tuple("this is string"))
print(tuple([1,2,3,4,5,6]))
('t', 'h', 'i', 's', ' ', 'i', 's', ' ', 's', 't', 'r', 'i', 'n', 'g')
(1, 2, 3, 4, 5, 6)
#membership
print(5 in (1,2,3,4,5,6))
print(10 not in (1,2,3,4,5))
True
True
Page | 18
#dict
Mutable mapping of keys to values
#{k1:v1,k2:v2,k3:v3}
#keys must be immutable
#values can be mutable
#order is arbitrary
d={"SriLanka":"Colombo","India":"Mumbai","France":"Paris","US":"NewYo
rk"}
print(d)
print(d['SriLanka'])
e={}
print(e)
{'US': 'NewYork', 'India': 'Mumbai', 'SriLanka': 'Colombo', 'France': 'Paris'}
Colombo
{}
names_ages=[('Sumudu',22),('Manusha',25),('Bob',34)]
d=dict(names_ages)
print(d)
{'Manusha': 25, 'Sumudu': 22, 'Bob': 34}
phonetic=dict(a='alpha',b='bravo',c='charly',d='delta')
print(phonetic)
{'b': 'bravo', 'a': 'alpha', 'd': 'delta', 'c': 'charly'}
Page | 19
#copy
x=d.copy()
print(x)
{'Manusha': 25, 'Sumudu': 22, 'Bob': 34}
f=dict(d)
print(f)
{'Manusha': 25, 'Sumudu': 22, 'Bob': 34}
#update
g=dict(Thilina=24,Nimal=21)
d.update(g)
print(d)
{'Manusha': 25, 'Sumudu': 22, 'Nimal': 21, 'Thilina': 24, 'Bob': 34}
#if keys already exists values will be replaced
for key in d:
print("{key} => {val}".format(key=key,val=d[key]))
Manusha => 25
Sumudu => 22
Nimal => 21
Thilina => 24
Bob => 34
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
Page | 21
#membership only work with keys
print("Sumudu" in d)
print("Manusha" not in d)
True
False
#delete
del d['Thilina']
print(d)
{'Manusha': 25, 'Sumudu': 22, 'Nimal': 21, 'Bob': 34}
#add
m={'H':[1,2,3],'He':[1,2],'Li':[3,4,5],'Be':[1]}
m['Be'] += [2,3,4,6]
print(m)
{'Li': [3, 4, 5], 'Be': [1, 2, 3, 4, 6], 'He': [1, 2], 'H': [1, 2, 3]}
m['N']=[7,6,8]
print(m)
{'Li': [3, 4, 5], 'Be': [1, 2, 3, 4, 6], 'He': [1, 2], 'N': [7, 6, 8], 'H': [1, 2, 3]}
Page | 22
#pretty printing
from pprint import pprint as pp
pp(m)
{'Be': [1, 2, 3, 4, 6],
'H': [1, 2, 3],
'He': [1, 2],
'Li': [3, 4, 5],
'N': [7, 6, 8]}
Page | 23
#range
Arithmetic progression of integers
print(range(5))
range(0, 5)
for i in range(5):
print(i)
0
1
2
3
4
print(list(range(5,10)))
print(list(range(2,10,2)))
[5, 6, 7, 8, 9]
[2, 4, 6, 8]
Page | 24
#enumerate for counters
t=[1,2,3,4,5,6]
for p in enumerate(t):
print(p)
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
for i,v in enumerate(t):
print("i={},v={}".format(i,v))
i=0,v=1
i=1,v=2
i=2,v=3
i=3,v=4
i=4,v=5
i=5,v=6
Page | 25
#set
Unordered collection of unique immutable objects
p={1,2,3,4,5,6}
print(p)
{1, 2, 3, 4, 5, 6}
s=set([1,2,3,5])
print(s)
{1, 2, 3, 5}
#empty
e=set()
#duplicates removed
s={1,2,3,1,2,3,5,6,7,7,7}
print(s)
{1, 2, 3, 5, 6, 7}
#order is arbitrary
for x in {1,2,3,4,5,1,2}:
print(x)
1
2
3
4
5
Page | 26
#membership
print(1 in s)
print(1 not in s)
True
False
#add
s.add(9)
print(s)
{1, 2, 3, 5, 6, 7, 9}
s.update([23,21])
print(s)
{1, 2, 3, 5, 6, 7, 9, 21, 23}
#remove
#value Error will rise if element is not in set
s.remove(23)
#no value error in discard
s.discard(21)
print(s)
{1, 2, 3, 5, 6, 7, 9}
Page | 27
#copy
p=s.copy()
q=set(s)
print(p,q)
{1, 2, 3, 5, 6, 7, 9} {1, 2, 3, 5, 6, 7, 9}
#set functions
#Boolean values will return
Page | 28
#Collection protocols
Protocol Implementing Collections
Container str, list, range, tuple, set, bytes, dict
Sized str, list, range, tuple, set, bytes, dict
Iterable str, list, range, tuple, set, bytes, dict
Sequence str, list, range, tuple, set, bytes
Mutable Sequence list
Mutable Set set
Mutable Mapping dict
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'}
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
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>
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
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

More Related Content

PDF
Arrays in python
PDF
Python Collections Tutorial | Edureka
PDF
Python Dictionary
PDF
Python-02| Input, Output & Import
PPTX
Array in c programming
PDF
PPTX
Dictionary in python
PPTX
Python Collections
Arrays in python
Python Collections Tutorial | Edureka
Python Dictionary
Python-02| Input, Output & Import
Array in c programming
Dictionary in python
Python Collections

What's hot (20)

PPTX
Arrays In C++
PDF
Introduction to NumPy (PyData SV 2013)
PPTX
Doubly linked list (animated)
PDF
Python functions
PDF
Python tuple
PPTX
Python-Encapsulation.pptx
PPTX
STRINGS IN PYTHON
PPTX
Tuple in python
PPTX
PDF
Immutable vs mutable data types in python
PPTX
Vector class in C++
PPTX
Chapter 06 constructors and destructors
PDF
Python list
PDF
Set methods in python
PPTX
Print input-presentation
PPT
Exception handling and function in python
PPTX
Python-DataAbstarction.pptx
PPTX
Chapter 05 classes and objects
Arrays In C++
Introduction to NumPy (PyData SV 2013)
Doubly linked list (animated)
Python functions
Python tuple
Python-Encapsulation.pptx
STRINGS IN PYTHON
Tuple in python
Immutable vs mutable data types in python
Vector class in C++
Chapter 06 constructors and destructors
Python list
Set methods in python
Print input-presentation
Exception handling and function in python
Python-DataAbstarction.pptx
Chapter 05 classes and objects
Ad

Similar to Python collections (20)

PPTX
UNIT-3 python and data structure alo.pptx
PDF
Introduction to python cheat sheet for all
PDF
PDF
Mementopython3 english
PDF
Mementopython3 english
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
PPTX
Intro Python Data Structures.pptx Intro Python Data Structures.pptx
PDF
Python_ 3 CheatSheet
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PDF
Python3 cheatsheet
PDF
python.pdf
PDF
Processing data with Python, using standard library modules you (probably) ne...
PPTX
Unit 4.pptx python list tuples dictionary
PPTX
PYTHON.pptx
PPTX
Pythonlearn-08-Lists for fundatmentals of Programming
PDF
Python Cheat Sheet
PPTX
Python list tuple dictionary .pptx
PPTX
fundamental of python --- vivek singh shekawat
PPTX
Python list tuple dictionary presentation
PPTX
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
UNIT-3 python and data structure alo.pptx
Introduction to python cheat sheet for all
Mementopython3 english
Mementopython3 english
ComandosDePython_ComponentesBasicosImpl.ppt
Intro Python Data Structures.pptx Intro Python Data Structures.pptx
Python_ 3 CheatSheet
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
Python3 cheatsheet
python.pdf
Processing data with Python, using standard library modules you (probably) ne...
Unit 4.pptx python list tuples dictionary
PYTHON.pptx
Pythonlearn-08-Lists for fundatmentals of Programming
Python Cheat Sheet
Python list tuple dictionary .pptx
fundamental of python --- vivek singh shekawat
Python list tuple dictionary presentation
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
Ad

More from Manusha Dilan (13)

PPTX
Cell aging
PPTX
Waterfall model
PPTX
Telco app development
PPTX
Jade Application Wedding Planner (Groom Assist)
PPTX
E commerce application using asp.net mvc4
PDF
Advanced python concepts
PDF
Ruhune maha wiharaya(රුහුණේ මහා විහාරය )
PDF
B2C Models
PPT
Selective repeat protocol
PPTX
Cellular concepts
PDF
Java_practical_handbook
PPTX
HCI_chapter_09-Evaluation_techniques
PPT
Lan technologies
Cell aging
Waterfall model
Telco app development
Jade Application Wedding Planner (Groom Assist)
E commerce application using asp.net mvc4
Advanced python concepts
Ruhune maha wiharaya(රුහුණේ මහා විහාරය )
B2C Models
Selective repeat protocol
Cellular concepts
Java_practical_handbook
HCI_chapter_09-Evaluation_techniques
Lan technologies

Recently uploaded (20)

PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharma ospi slides which help in ospi learning
PPTX
GDM (1) (1).pptx small presentation for students
Module 4: Burden of Disease Tutorial Slides S2 2025
STATICS OF THE RIGID BODIES Hibbelers.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
O5-L3 Freight Transport Ops (International) V1.pdf
PPH.pptx obstetrics and gynecology in nursing
Supply Chain Operations Speaking Notes -ICLT Program
Complications of Minimal Access Surgery at WLH
O7-L3 Supply Chain Operations - ICLT Program
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Cell Structure & Organelles in detailed.
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Microbial disease of the cardiovascular and lymphatic systems
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Basic Mud Logging Guide for educational purpose
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
102 student loan defaulters named and shamed – Is someone you know on the list?
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharma ospi slides which help in ospi learning
GDM (1) (1).pptx small presentation for students

Python collections

  • 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]
  • 16. Page | 15 #tuple Heterogeneous immutable sequence t=("This","Is",23,43.5) print(t[3]) 43.5 print(len(t)) 4 print(t) ('This', 'Is', 23, 43.5) for item in t: print(item) This Is 23 43.5 #concatenate print(t+("new",66)) ('This', 'Is', 23, 43.5, 'new', 66) #repeat print(t*3) print(type(t)) ('This', 'Is', 23, 43.5, 'This', 'Is', 23, 43.5, 'This', 'Is', 23, 43.5) <class 'tuple'>
  • 17. Page | 16 #nested tuple a=((1,2),(1,3)) print(a[1]) print(a[1][0]) (1, 3) 1 #single tuple by adding trailing comma k=(99,) #empty tuple e=() #sequence take as tuple p=1,2,3,4,5,4 print(p) (1, 2, 3, 4, 5, 4) #tuple are useful for multiple return values def minmax(item): return min(item),max(item) print(minmax([1,3,45,3,4,2,22])) (1, 45)
  • 18. Page | 17 #tuple unpacking lower,upper=minmax([3,2,11,4,5,7,8,44,0]) print(lower) print(upper) 0 44 #tuple unpacking works with nested tuples (a,(b,(c,d)))=(4,(6,(3,5))) print(b) 6 #idiomitic python swap #a,b=b,a #converting to tuple print(tuple("this is string")) print(tuple([1,2,3,4,5,6])) ('t', 'h', 'i', 's', ' ', 'i', 's', ' ', 's', 't', 'r', 'i', 'n', 'g') (1, 2, 3, 4, 5, 6) #membership print(5 in (1,2,3,4,5,6)) print(10 not in (1,2,3,4,5)) True True
  • 19. Page | 18 #dict Mutable mapping of keys to values #{k1:v1,k2:v2,k3:v3} #keys must be immutable #values can be mutable #order is arbitrary d={"SriLanka":"Colombo","India":"Mumbai","France":"Paris","US":"NewYo rk"} print(d) print(d['SriLanka']) e={} print(e) {'US': 'NewYork', 'India': 'Mumbai', 'SriLanka': 'Colombo', 'France': 'Paris'} Colombo {} names_ages=[('Sumudu',22),('Manusha',25),('Bob',34)] d=dict(names_ages) print(d) {'Manusha': 25, 'Sumudu': 22, 'Bob': 34} phonetic=dict(a='alpha',b='bravo',c='charly',d='delta') print(phonetic) {'b': 'bravo', 'a': 'alpha', 'd': 'delta', 'c': 'charly'}
  • 20. Page | 19 #copy x=d.copy() print(x) {'Manusha': 25, 'Sumudu': 22, 'Bob': 34} f=dict(d) print(f) {'Manusha': 25, 'Sumudu': 22, 'Bob': 34} #update g=dict(Thilina=24,Nimal=21) d.update(g) print(d) {'Manusha': 25, 'Sumudu': 22, 'Nimal': 21, 'Thilina': 24, 'Bob': 34} #if keys already exists values will be replaced for key in d: print("{key} => {val}".format(key=key,val=d[key])) Manusha => 25 Sumudu => 22 Nimal => 21 Thilina => 24 Bob => 34
  • 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
  • 22. Page | 21 #membership only work with keys print("Sumudu" in d) print("Manusha" not in d) True False #delete del d['Thilina'] print(d) {'Manusha': 25, 'Sumudu': 22, 'Nimal': 21, 'Bob': 34} #add m={'H':[1,2,3],'He':[1,2],'Li':[3,4,5],'Be':[1]} m['Be'] += [2,3,4,6] print(m) {'Li': [3, 4, 5], 'Be': [1, 2, 3, 4, 6], 'He': [1, 2], 'H': [1, 2, 3]} m['N']=[7,6,8] print(m) {'Li': [3, 4, 5], 'Be': [1, 2, 3, 4, 6], 'He': [1, 2], 'N': [7, 6, 8], 'H': [1, 2, 3]}
  • 23. Page | 22 #pretty printing from pprint import pprint as pp pp(m) {'Be': [1, 2, 3, 4, 6], 'H': [1, 2, 3], 'He': [1, 2], 'Li': [3, 4, 5], 'N': [7, 6, 8]}
  • 24. Page | 23 #range Arithmetic progression of integers print(range(5)) range(0, 5) for i in range(5): print(i) 0 1 2 3 4 print(list(range(5,10))) print(list(range(2,10,2))) [5, 6, 7, 8, 9] [2, 4, 6, 8]
  • 25. Page | 24 #enumerate for counters t=[1,2,3,4,5,6] for p in enumerate(t): print(p) (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) for i,v in enumerate(t): print("i={},v={}".format(i,v)) i=0,v=1 i=1,v=2 i=2,v=3 i=3,v=4 i=4,v=5 i=5,v=6
  • 26. Page | 25 #set Unordered collection of unique immutable objects p={1,2,3,4,5,6} print(p) {1, 2, 3, 4, 5, 6} s=set([1,2,3,5]) print(s) {1, 2, 3, 5} #empty e=set() #duplicates removed s={1,2,3,1,2,3,5,6,7,7,7} print(s) {1, 2, 3, 5, 6, 7} #order is arbitrary for x in {1,2,3,4,5,1,2}: print(x) 1 2 3 4 5
  • 27. Page | 26 #membership print(1 in s) print(1 not in s) True False #add s.add(9) print(s) {1, 2, 3, 5, 6, 7, 9} s.update([23,21]) print(s) {1, 2, 3, 5, 6, 7, 9, 21, 23} #remove #value Error will rise if element is not in set s.remove(23) #no value error in discard s.discard(21) print(s) {1, 2, 3, 5, 6, 7, 9}
  • 28. Page | 27 #copy p=s.copy() q=set(s) print(p,q) {1, 2, 3, 5, 6, 7, 9} {1, 2, 3, 5, 6, 7, 9} #set functions #Boolean values will return
  • 29. Page | 28 #Collection protocols Protocol Implementing Collections Container str, list, range, tuple, set, bytes, dict Sized str, list, range, tuple, set, bytes, dict Iterable str, list, range, tuple, set, bytes, dict Sequence str, list, range, tuple, set, bytes Mutable Sequence list Mutable Set set Mutable Mapping dict
  • 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