10. Data Collections v2 (1)
10. Data Collections v2 (1)
Non-Sequential
Data Collections
1
Outline
• Lists
• Tuples
• Dictionary
• Set
• Operations of all …
• Adding and Deleting Elements
• Operators and Sets
• Looping and Sets
2
languages = ['English', 'Hindi', 'Chinese', 'Spanish', 'Bengali’]
LISTS
Number list
• You can create a series of numbers
using range() function.
num = list(range(1,
11))
print(num)
# output
# [1, 2, 3, 4, 5, 6, 7, 8, 9,
10]
4
Looping through lists
programmingLanguages = ['python', 'java’, ‘c']
for pl in programmingLanguages:
print("I know how to code in " + pl.title() +
" programming language.")
# output
# I know how to code in Python programming
language.
# I know how to code in Java programming
language.
5
# I know how to code in C programming
language.
range() function with for loop
print(min(num # 1
))
print(max(nu # 10
m)) 7
print(sum(nu # 55
List comprehension
• List comprehension is an advanced approach to
generating lists. List comprehension allows you
to combine for loop to create a list.
# without list
comprehension
cubes = []
for i in range(1,11):
cube = i ** 3
cubes.append(cube)
print(cubes) # with list comprehension
cubes = [c ** 3 for c in range(1,11)]
print(cubes) 8
# output
# [1, 8, 27, 64, 125, 216, 343, 512, 729,
Slicing List
languages = ['English', 'Hindi', 'Chinese', 'Spanish',
'Bengali', 'Russian', 'Arabic', 'Portuguese']
# print list containing – english to 0 'English’
bengali
print(languages[0:5]) 1 'Hindi’
# ['English', 'Hindi', 'Chinese', 2 'Chinese’
'Spanish', 'Bengali']
# print list contains bengali, russian 3 'Spanish’
and arabic
print(languages[4:7]) 4 'Bengali’
# ['Bengali', 'Russian', 'Arabic'] 5 'Russian’
# python by default start from the 6 'Arabic’
beginning.
print(languages[:3]) 7 'Portugues
e 9
# ['English', 'Hindi', 'Chinese']
Copying a List
languages = ['English', 'Hindi', 'Chinese',
'Spanish', 'Bengali', 'Russian', 'Arabic',
'Portuguese']
copy_languages = languages [ : ]
print(languages)
print(copy_languages)
10
Copying a List
languages = ['English', 'Hindi', 'Chinese',
'Spanish', 'Bengali', 'Russian', 'Arabic',
'Portuguese']
copy_languages = languages
print(languages)
print(copy_languages)
11
languages = ('English', 'Hindi', 'Chinese', 'Spanish', 'Bengali')
12
TUPLES
Tuples
• Like lists, tuples are collection types in python.
• Tuple use parentheses “(“ ,“)”.
dimensions =
(100, 20)
output
print(dimensions[0 100
])
print(dimensions[1 20
• Tuples are immutable,
])
• which means the value of immutable lists cannot
13
change.
Tuples are like lists
• Tuples are another kind of sequence that
function much like a list - they have elements
which are indexed starting at 0
>>> x = ['Glenn', 'Sally', 'Joseph’]
>>> print (x[2])
Joseph
>>> x = ('Glenn', 'Sally', 'Joseph')
>>> y = [1, 9, 2 ]
>>> print
>>> print (y) (x[2])
Joseph
[1, 9, 2]
= ( 1, 9, 2 )
>>> y max(y)
>>> print
9 >>> print (y)
>>> for iter in y:
(1, 9, 2)
print (iter)
>>> print max(y)
1
9
9 14
2
..but.. Tuples are "immutable"
• Unlike a list, once you create a tuple, you cannot alter its
contents - similar to a string
>>> x = [9, 8, 7]
>>> x[2] = 6
>>> print (x)
[9, 8, 6]
>>> y = 'ABC’
>>> y[2] = ‘D’
Traceback: 'str' object does not support item Assignment
15
>>> z = (5, 4, 3)
>>> z[2] = 0
Modify tuple
• As tuple is immutable but we can overwrite
tuple, we can completely change tuple values.
dimensions = (100, 20) # output
print(dimensions) # (100, 20)
# assign new values to
tuple
dimensions = (500,
100)
print(dimensions) # (500, 100)
16
unpack a tuple
• We can unpack a tuple by assigning it to a
comma-separated list of variables
dimensions = (100, 20)
X_axis , Y_axis = output
dimensions
print(X_axis) 100
print(Y_axis) 20
17
Looping trough all tuple values
• we can loop through tuples as we did with a list.
20
Tuples are more efficient
• they are simpler and more efficient in terms of
memory use and performance than lists
• So in our program when we are making "temporary
variables" we prefer tuples over lists.
• We can also put a tuple on the left hand side of an
assignment statement
•
>>> (x, y) = (4, 'fred’)
>>> print (y)
fred
>>> (a, b) = (99, 98) 21
>>> print (a)
99
Tuples are Comparable
• The comparison operators work with tuples and
other sequences If the first item is equal, Python goes
on to the next element, and so on, until it finds
elements that differ.
>>> (0, 1, 2) < (5, 1, 2)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
>>> ( 'Jones', 'Sally' ) < ('Jones', 'Sam’)
True
>>> ( 'Jones', 'Sally') > ('Adams', 'Sam’) 22
True
Try it by yourself
def calculator(X,Y):
W=X+Y
Z=X*Y
return W,Z
X=3
Y=4
res=calculator(X,Y)
print(res)
print(type(res)) 23
Question
• We have the following :
>>> t = ([1,2,3], 'Hello')
This tuple containing a list.
What should we do to change the
list to
[4,5]
24
languages = {'eg':'English', 'hi':'Hindi', 'ch':'Chinese', ‘sp':'Spanish'}
DICTIONARIES 25
Dictionaries
• Dictionaries are a collection of key and value pairs.
• each key is associated/connected with values.
• To access any value, we have to use the key, which
is associated with value.
• We can use any data object as key or value
print(personal)
# output
# {'fname': 'Durgesh', 'lname': 'Samariya',
'age': 28, 'city':'Melbourne'}
# output
for value in personal.values(): # Durgesh
print(value) # Samariya
# 28
34
Dictionary Operations
• items
• Returns a list of (key, value) pairs.
>> print ( list( Codes.items() ))
[('Mobinil', '012'), ('Etisalat', '011'), ('Vodafone', '010')]
• get
• Returns the value associated with a key.
>> print ( Codes.get( ‘Mobinil’ ))
‘012’
35
Ex 1
personal = { 'fname' : 'Durgesh', 'lname' :
'Samariya', 'age' : 28 }
# output
for key, value in personal.items():# fname
print(key) # Durgesh
print(value) # lname
# Samariya
# age
# 28
# Durgesh
print (personal.get('fname’)) # Samariya
print (personal.get(‘lname’)) # 28
36
print (personal.get(‘age’))
Dictionary Operations
• clear
• Empties the dictionary.
>> Codes.clear()
• update
• Updates the dictionary with the contents of
another.
Codes2 = {'Cairo':'02', 'Alex':'03'}
Codes.update(Codes2)
#output 37
print(personal)
38
Example
personal = { 'fname' : 'Durgesh', 'lname' :
'Samariya', 'age' : 28 }
person0 = { 'fname0' : 'Nouh', 'lname0' : 'Sara',
'age0' : 20 }
personal.update(person0)
print(personal)
39
Ex.
personal = { 'fname' : 'Durgesh', 'lname' :
'Samariya', 'age' : 28 }
person0 = { 'fname' : ‘Nouh', 'lname' : 'Sara', 'age’
: 20 }
person0.clear()
print(person0)
# {}
40
Nested Dictionary
• you can store dictionaries in the list or vice versa.
person1 = {'name':'Person1', 'age':28}
person2 = {'name':'Person2', 'age':15}
person3 = {'name':'Person3', 'age':40}
persons = [person1, person2, person3]
for person in persons:
print(person)
# output
# {'name': 'Person1', 'age': 28}
# {'name': 'Person2', 'age': 15} 41
# output
for key,value in name
person.items():
print(key) ['Durgesh',
'Samariya']
print(value) age
27
Can you store a dictionary in the dictionary? 42
movies = {
'avatar': {'year': 2009,
'rating': 5},
'inception’ : {'year': 2010,
'rating’: 5},
'joker’ : {'year': 2019, 'rating':
4.5},
}
print(movies['avatar'])
# output
# {'year': 2009, 'rating': 5}
43
print(movies['avatar']['year'])
languages = set(['English', 'Hindi', 'Chinese', 'Spanish'])
SETS 44
What is a Set?
• A set is an unordered collection of distinct items
>>> s = set([1, 2, 3, 4, 1, 2])
>>> print (s) duplicates
removed
{1, 2, 3, 4}
>>> L = ['a','b','D','d','a']
>>> s = set (L)
>>> print (s)
‘d’ ≠ ‘D’
{'a', 'b', 'D', 'd’}
>>>s = set() # empty set 45
>>> print(s)
{}
Adding and Deleting Elements
• To add an element to a set use add()
• Example:
>>> s.add(12) => s = {1,2,3,4,12}
• To delete an element from a set use remove()
• Example:
>>> s.remove(3) => s = {1,2,4,12}
• To delete all elements from a set use clear()
• Example:
>>> s.clear() 46
Returns None
Set Operations
Div2 = set ([2,4,6]) Div3 = set ([3,6,9])
• union
• Creates a set with elements that are in either
set
>>> Div2.union(Div3) => {2, 3, 4, 6, 9}
• intersection
• Creates a set with elements that are in both
sets
>>> Div2.intersection(Div3) => {6} 47
Set Operations Div2 = set ([2,4,6])
Div3 = set ([3,6,9])
• difference
• Creates a set with elements from one set, but
not the other
>>> Div2.difference(Div3) => {2, 4}
• symmetric_difference
• Creates a set with elements that are in exactly
one set
>>> Div2.symmetric_difference(Div3)
{9, 2, 3, 4} 48
Set Operations
S1 = set([2,4]) S2 = set([1,2,3,4])
• issubset
• Asks are all of one set’s elements contained in
another?
>>> S1.issubset(S2) => True
• issuperset
• Asks does one set contain all of another’s
elements?
>>> S1.issuperset(S2) => False 49
Operators and Sets
50
Looping and Sets
• If you use a Set in a for statement, it traverses the
elements of the set
• Example:
s = set([1,2,3,4])
for e in s:
print (e)
• Result:
1
2
3 51
4
in Operator
• To check membership of an element.
>print ( '#' in 'Hi#’)
True
>print ( 3 in [4,5,6])
False
>print (7 in {6: 'Ahmed’, 7: 'Belal’})
True
>if 9 in {8,6}:
? 52
PROBLEMS 53
What does this code do???
54
55
Resolve Q1 in Sheet 6
Write a program that takes two lists and prints a
list containing the common elements between
the two lists.
56
Summary
• Strings “..” indexed
immutable
• Lists [..] indexed mutable
• Tuples (..) indexed
immutable
• Dictionaries {..} unordered mutable
• Sets set( [ list] ) unordered mutable
57