SlideShare a Scribd company logo
1 of 34
Download to read offline
#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

What's hot

What's hot (20)

Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Sets in python
Sets in pythonSets in python
Sets in python
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Expression trees
Expression treesExpression trees
Expression trees
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Pseudo code of stack Queue and Array
Pseudo code of stack Queue and ArrayPseudo code of stack Queue and Array
Pseudo code of stack Queue and Array
 
Priority queues
Priority queuesPriority queues
Priority queues
 
Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
 

Similar to Python collections

intro_to_python_20150825
intro_to_python_20150825intro_to_python_20150825
intro_to_python_20150825
Shung-Hsi Yu
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
Siva Arunachalam
 
Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
Ohgyun Ahn
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
pugpe
 

Similar to Python collections (20)

Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Python lists
Python listsPython lists
Python lists
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
python_lab_manual_final (1).pdf
python_lab_manual_final (1).pdfpython_lab_manual_final (1).pdf
python_lab_manual_final (1).pdf
 
intro_to_python_20150825
intro_to_python_20150825intro_to_python_20150825
intro_to_python_20150825
 
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
QMC: Undergraduate Workshop, Tutorial on 'R' Software - Yawen Guan, Feb 26, 2...
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
Session -5for students.pdf
Session -5for students.pdfSession -5for students.pdf
Session -5for students.pdf
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
 
Raspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry PiRaspberry Pi - Lecture 5 Python for Raspberry Pi
Raspberry Pi - Lecture 5 Python for Raspberry Pi
 
Practice_Exercises_Data_Structures.pptx
Practice_Exercises_Data_Structures.pptxPractice_Exercises_Data_Structures.pptx
Practice_Exercises_Data_Structures.pptx
 
Pre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to ElixirPre-Bootcamp introduction to Elixir
Pre-Bootcamp introduction to Elixir
 

More from Manusha Dilan

More from Manusha Dilan (13)

Cell aging
Cell agingCell aging
Cell aging
 
Waterfall model
Waterfall modelWaterfall model
Waterfall model
 
Telco app development
Telco app developmentTelco app development
Telco app development
 
Jade Application Wedding Planner (Groom Assist)
Jade Application Wedding Planner (Groom Assist)Jade Application Wedding Planner (Groom Assist)
Jade Application Wedding Planner (Groom Assist)
 
E commerce application using asp.net mvc4
E commerce application using asp.net mvc4E commerce application using asp.net mvc4
E commerce application using asp.net mvc4
 
Advanced python concepts
Advanced python conceptsAdvanced python concepts
Advanced python concepts
 
Ruhune maha wiharaya(රුහුණේ මහා විහාරය )
Ruhune maha wiharaya(රුහුණේ මහා විහාරය )Ruhune maha wiharaya(රුහුණේ මහා විහාරය )
Ruhune maha wiharaya(රුහුණේ මහා විහාරය )
 
B2C Models
B2C ModelsB2C Models
B2C Models
 
Selective repeat protocol
Selective repeat protocolSelective repeat protocol
Selective repeat protocol
 
Cellular concepts
Cellular conceptsCellular concepts
Cellular concepts
 
Java_practical_handbook
Java_practical_handbookJava_practical_handbook
Java_practical_handbook
 
HCI_chapter_09-Evaluation_techniques
HCI_chapter_09-Evaluation_techniquesHCI_chapter_09-Evaluation_techniques
HCI_chapter_09-Evaluation_techniques
 
Lan technologies
Lan technologiesLan technologies
Lan technologies
 

Recently uploaded

Recently uploaded (20)

How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

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