Python collections

34
#Python Collections P.D. Manusha Dilan [email protected] 2015-August-15

Transcript of Python collections

#Python Collections

P.D. Manusha Dilan

[email protected]

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:\Users\Exam\Doc\dir"

print(path)

C:\Users\Exam\Doc\dir

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