0% found this document useful (0 votes)
27 views25 pages

CSC1041 Session 10 Python Collection Data Types

This document provides an overview of common collection data types in Python including lists, tuples, dictionaries, and sets. It describes how to create, access, modify, and iterate through each type of collection. Key points include: lists are ordered and changeable, tuples are ordered but unchangeable, dictionaries use keys to map to values, and sets are unordered and do not allow duplicates. Examples are given for common operations like adding, removing, and retrieving items from each collection type.

Uploaded by

pasan lahiru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
27 views25 pages

CSC1041 Session 10 Python Collection Data Types

This document provides an overview of common collection data types in Python including lists, tuples, dictionaries, and sets. It describes how to create, access, modify, and iterate through each type of collection. Key points include: lists are ordered and changeable, tuples are ordered but unchangeable, dictionaries use keys to map to values, and sets are unordered and do not allow duplicates. Examples are given for common operations like adding, removing, and retrieving items from each collection type.

Uploaded by

pasan lahiru
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

CSC 1041

Programming Laboratory I

Session 11

Collection Data types in Python (Lists, Tuples,


Dictionaries, Sets)

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 1


Store a collection of data in Python
• Python has some useful built-in data types

• They are divided into categories as shown below


Text type :str
Numeric type :int, float, complex
Sequence type :list, tuple, range
Mapping type :dict
Set types :set, frozenset
Boolean type :bool

• list, tuple, dict and set are the 4 built-in data types in Python
that can store collection of data

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 2


List
• Lists are used to store multiple items in a single variable
• Lists are:
Ordered – Items have a defined order, and that order will not change
Changeable – Items can be changed, added, and removed after the
list has been created
Allowing duplicates – Can have items with same value

List Creation
l i s t 1 = ["Kandy","Colombo","Galle","Kandy"]
print(list1)

• Lists can contain values of different data types

l i s t 2 = ["Kandy",130,True,22.2]
print(list2)

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 3


List Cont…
Accessing list items
l i s t 1 = [ "K a n d y " , "C o l o m b o" , " G a l l e" , " J a f fn a " , " A m pa r a " ]
print ( l i s t 1 [ 0 ] )

p ri nt ( l i s t 1 [ - 1 ] ) # negative indexing is starting from the end of the list


print( l is t 1[ 1 :3 ] )
print( list1[:3] )
print( list1[2:] )

Checking whether an item exists in list


if "Colombo" i n l i s t 1 :
print ("C olo mbo i s i n th e l i s t " )

Changing list items


list1[1] = "Nuwara e l i y a "
list1[1:3] = ["Anu radhapura" ,"Kataraga ma"]
list1[1:2] = [ "A nu rad ha pu ra" ," Kataragama"]
list1[1:3] = ["P olo nna ruwa "]

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 4


List Cont…
Add List Items

• append() will add the item to the end of the list

• We can use insert() to add item to a specific location

• We can use extend() to append items from another collection


data type to the current list

l i s t 1 = ["Kand y", "C olo mbo ", "Ga lle "," Ja ffn a", "Am pa ra" ]
list1.append("Kataragama")
lis t1 .i ns er t( 2, "M at ar a" )

l i s t 2 = ["Mannar","Kataragama"]
l i s t 1 . e xt e n d ( li s t 2 )

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 5


List Cont…
Remove Items from a List

• remove() can be used to remove a specific item from the list

• pop() removes the specified index

• del remove the specified index

• clear() empties the list. The list remains, but no content

l i s t 1 = ["Kandy "," Col omb o" ,"G all e", "J aff na" ," Amp ara "]
l i s t 1 . r e m o v e (" G a l l e " )
list 1. pop ()
de l l i s t [ 0 ]
l i s t 1 . clear( )

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 6


List Cont…
Retrieve Items
• Iterate through list using a for Loop

l i s t 1 = [ " K a n d y " , " C o l o m b o " , " G a l l e " ," J a f f n a ", " A m p a ra " ]

# Method 1
for i in list1:
pr i nt ( i )

• Using range() and len() we can access the indexes of the list

# Method 2
f o r i i n range( l e n ( l i s t 1 ) ) :
print( li s t1 [ i] )

• List comprehension offers the shortest syntax to retrieve items from list

# Method 3
[ print(i) for i in list1 ]
CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 7
List Cont…
• Write a program using a for loop to reverse the given list

l i s t 1 = ["N ", "O " ," H" ," T" ," Y ", "P "]

list2 = []

for i i n range( l e n ( l i s t 1 ) ) :
list2.insert( i , list1[-1] )
l i s t1 . p op ( )

print(list2)

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 8


Tuple
• Tuple also stores items of different variable types

• Tuples are faster than lists (accessing items and iteration)

• Tuple is ordered but unchangeable (cannot add or remove items after


tuple is created)

• It also allows duplicate values

Tuple Creation

tupl e1 = (" S r i L a n k a " , " In d i a" , " Pa k i st a n " ," R u ss i a ”)

• If declaring a tuple with one value, remember to add the comma (,)

tupl e1 = ( " S r i Lan ka" ,)

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 9


Tuple Cont…
Tuple Access

tupl e1 = (" S r i L a n k a " , " In d i a" , " Pa k i st a n " ," R u ss i a ”)

• Access tuple by index


pr i nt (t u pl e 1[ 1] )
p r i nt ( t up l e1 [ -1 ]) # negative indexing is starting from the end of the tuple
pr i nt ( t upl e1[ 2: 3] )
p r i n t (t u p le 1 [ :4 ] )
p r i n t (t u p le 1 [ :2 ] )

• Check if an item exists


if " I nd ia " i n tuple1:
p r i n t ( " I n d i a i s i n the t u p l e " )

• To count number of times an item occurs in a tuple we can use the


count() method
t u p l e 1 . c o u n t (" S r i Lanka")
CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 10
Tuple Cont…
• Since tuples are unchangeable, you cannot change, add, remove items in a
tuple once it is created

Add Tuple to Tuple


• You are not allowed to add new items to tuples, but you can add a tuple to
an existing tuple

tupl e1 = (" S r i L a n k a " , " In d i a" , " Pa k i st a n " ," R u ss i a " )


tupl e2 = (" USA" ,)
#tuple2 = ( " A u s t r a l i a " , " E n g l a n d " )

tupl e1 += t upl e2
pri nt (tu pl e1 )

Delete tuple completely

tupl e1 = (" S r i L a n k a " , " In d i a" , " Pa k i st a n " ," R u ss i a ”)


de l tup le 1

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 11


Tuple Cont…
Retrieve Items
• Like in the lists, we can use for loops to loop through tuples as well.
Eg:
tuple1 = ( " S r i L anka ","I ndi a"," Paki stan "," Russ ia")

for i i n tuple1:
print(i)

• Similarly, we can use range() and len() to refer items using the index
• We could also use a while loop

t u p l e 1 = (" S r i L a n k a " , " I n d i a " , " P a k i s t a n " , " R u s s i a " )


i = 0
whil e i < l e n ( t u p l e 1 ) :
print(tuple1[i])
i = i + 1

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 12


Set
• A set can store data of different data types

• A set is unordered

• A set is unindexed

• A set is unchangeable (can add items but cannot change existing items)

• A set does not allow duplicates

Set Creation
set1 = { 1 2 0 , 5 0 . 4 , " S r i Lanka",True}
pri nt (se t1 )

set2 = { 1 2 0 , 50 . 4, T r ue , "S r i Lanka",120}


pri nt (se t2 )

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 13


Set Cont…
Set Item Access
• Cannot access items using the index because sets are unindexed

set1 = { 1 2 0 , 5 0 . 4 , " S r i Lanka",True}


pri nt (se t1 )

f o r x i n set1:
print(x)

Add Items to Set


• We can add items to a set using the update() function.

set1 = { " A " , " B " , " C " , " D " }


set2 = { " E " , " F " , " G " }

set1. upd ate (set 2)

• We can use other collection data types (tuple, list, etc) to update

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 14


Set Cont…
Delete Item
• Can use both remove() and discard() to delete items from a set. If the
removing item does not exist in the set, discard() will not raise an error but
remove will raise an error.

set1 = { 1 2 0 , 5 0 . 4 , " S r i Lanka",True}


set1.remo ve("Sr i Lanka")

set 1. re mo ve (" In di a" )


set1.discard("I ndia")

• Can use pop() to delete items but since it removes the last element, the
deleted element is not predictable because a set is unordered.

set1 = { 1 2 0 , 5 0 . 4 , " S r i Lanka",True}


item1 = s et 1. pop ()
print(ite m1)

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 15


Set Cont…
Set Joining

• We can use union() method to create a new set with items in both sets
set1 = { 1 2 0 , 5 0 . 4 , " S ri Lanka",True}
set2 = {"India",False,100}

set3 = set 1. un io n( se t2 )
pri nt (se t3 )

• We can use intersection() to return a new set that contain items available
in both sets only
set1 = { 1 2 0 , 5 0 . 4 , " S ri Lanka",True}
set2 = { " I n d i a " , F a l s e , 1 0 0 , 5 0 . 4 , " S r i Lanka"}

set3 = s e t 1 . i n t e r s e c t i o n ( s e t 2 )

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 16


Dictionary
• Dictionaries store data in key-value pairs
• Dictionaries are ordered *from python version 3.7, dictionaries are ordered*
• Dictionaries are changeable (can change, add or remove items after
creation)
• Dictionaries do not allow duplicates (do not allow duplicated keys)

Dictionary Creation
dict1 = {
" c o u n t r y " : " S r i Lanka" ,
" c i t y " : " Perade niya" ,
"reg ion ": "Central"
}

• Dictionaries can be referred to by using the key name

p r i n t (d i c t1 [ "r e gi o n "] )

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 17


Dictionary Cont…
• Does not allow duplicate keys

dict1 = {
" c o u n t r y " : " S r i Lanka" ,
" c i t y " : " Perade niya“ ,
" c i t y " : " Kandy" ,
"reg ion ": "Central"
}
p r i n t ( d ic t 1 )

• Values in a dictionary can be of any data type

dict1 = {
" c o u n t r y " : " S r i Lanka" ,
" c i t y " : " Perade niya" ,
" language s" : [ " S i n h a l e s e " , " T a m i l " , " E n g l i s h " ] ,
"reg ion ”:"Central"
}

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 18


Dictionary Cont…
Access Items
dict1 = {
" c o u n t r y " : " S r i Lanka" ,
" c i t y " : " Perade niya" ,
"reg ion ": "Central"
}

item1 = d i c t 1 . g e t ( " c i t y " )

• keys() will get the list of keys in the dictionary and values() will get the list
of values
dict_keys = d i c t 1 . k e y s ( )
dict _v alu es = d i c t 1 . v a l u e s ( )

• Items() will get the list of key-value pairs


dic t_ it em s = d i c t 1 . i t e m s ( )

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 19


Dictionary Cont…
Retrieve Items
dict1 = {
" c o u n t r y " : " S r i Lanka" ,
" c i t y " : " Peradeniy a" ,
"reg ion ": "Central"
}

• To return the keys in a dictionary


for i i n dict1. keys ():
print(i)

• To return the values in a dictionary


for i in dict1.v alu es( ):
print(i)

• To return both key value pairs


for i , j i n d ic t1. it em s( ):
print(i,j)
CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 20
Dictionary Cont…
Change Items/Update Items
dict1 = {
" c o u n t r y " : " S r i Lanka" ,
" c i t y " : " Peradeniy a" ,
"reg ion ": "Central"
}

• Change values by referring the key

d i c t 1 [ " c i t y " ] = " Kandy"


p r i n t ( d ic t 1 )

• Update an existing dictionary by using update()

dict1.update({ "city":"K andy"})


p r i n t ( d ic t 1 )

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 21


Dictionary Cont…
Remove Items
• We can use pop() to remove items of a specified key

dict1 = {
" c o u n t r y " : " S r i Lanka" ,
" c i t y " : " Peradeniy a" ,
"reg ion ": "Central"
}
di ct 1. pop( " count r y" )
p r i n t ( d ic t 1 )

• Can use popitem() to remove the last inserted item

d i c t1 . p op i te m ()

• We can use del to completely delete a dictionary and clear() to empty


the dictionary
de l d i c t 1
di c t1 .c l ea r ()

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 22


Dictionary Cont…
Exercise

• Develop a program to read integer values in a list and append values to a


dictionary containing two keys to store numbers greater than 50 and less
than fifty.
Input numbers – 70,54,33,48,1000,12,7,98

Output(Print the following dictionary):

number_dict = {
"grea ter _th an_5 0": [70 ,54, 100 0,9 8],
"le ss _th an _5 0": [3 3, 48 ,12 ,7 ]
}

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 23


Dictionary Cont…
Answer
d i c t 1 = { " g r e a t e r _ t h a n _ 5 0 " :[ ] ,
" l e s s _ t ha n _ 5 0 ": [ ] }

number_list = [ ]

for i i n rang e(8 ):


number_li st.app end(in put("E nter t he number: " ) )

for i i n numbe r_l ist :


i f i n t ( i ) > 50:
di ct 1[ " gr eat er _t han_50" ] . append( i )
e l i f i n t ( i ) < 50:
di ct 1[ " le ss _t ha n _5 0" ]. a pp en d( i )

p r i n t ( d ic t 1 )

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 24


SUMMARY
• The four built-in data types in Python to save collection of data are list,
tuple, set and dictionary

LIST TUPLE SET DICTIONARY

Can contain Can contain Can contain


Can contain
different data different data different data
different data
types in one tuple types in one set types in different
types in one list
keys and values

Ordered Ordered Unordered Ordered

Unchangeable (can
add items but
Changeable Unchangeable Changeable
cannot change
existing item)

Allow duplicates Allow duplicates No duplicates No duplicates

Indexed Indexed Unindexed Key-value pairs

CSC 1041 Department of Statistics and Computer Science , University of Peradeniya. 25

You might also like