0% found this document useful (0 votes)
5 views57 pages

10. Data Collections v2 (1)

The document provides an introduction to non-sequential data collections in Python, covering lists, tuples, dictionaries, and sets. It explains operations such as adding and deleting elements, looping, and demonstrates the use of various data structures with examples. Additionally, it highlights the differences between mutable and immutable types, particularly focusing on the characteristics and functionalities of tuples and dictionaries.

Uploaded by

nivido4274
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views57 pages

10. Data Collections v2 (1)

The document provides an introduction to non-sequential data collections in Python, covering lists, tuples, dictionaries, and sets. It explains operations such as adding and deleting elements, looping, and demonstrates the use of various data structures with examples. Additionally, it highlights the differences between mutable and immutable types, particularly focusing on the characteristics and functionalities of tuples and dictionaries.

Uploaded by

nivido4274
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Introduction to

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

for i in range(1,11) : # output


print(i) # 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8 6
# 9
# 10
Recap List operations
num = list(range(1,11))
# output
print(num) # [1, 2, 3, 4, 5, 6, 7,
8, 9, 10]

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.

dimensions = (100, 20) #


output
# 100
for dimension in dimensions: # 20
print(dimension)
• They are mostly used when programmers want
to store some value that can not be changed
throughout the program. 18
Things not to do with tuples
>>> x = (3, 2, 1)
>>> x.sort()
Traceback:AttributeError: 'tuple' object has no
attribute 'sort’
>>> x.append(5)
Traceback:AttributeError: 'tuple' object has no
attribute 'append’
>>> x.reverse()
Traceback:AttributeError: 'tuple' object has no
attribute 'reverse’ 19
A Tale of Two Sequences
• >>> l = list()
>>> dir(l)
['append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
• >>> t = tuple()
>>> dir(t)
['count', 'index']

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

myInformation = { 'name': 'Durgesh',


'age': 28 }
#
output
26
print(myInformation['name']) Durge
sh
What is a Dictionary?
• A Dictionary is an unordered, mutable collection of
key-value pairs
• Example:
• Codes = {‘Mobinil’: ‘012’, ‘Vodafone’: ‘010’}
>> Codes[‘Mobinil’]
012 Note the [ ]
>> Codes[‘Vodafone’]
010
>> Codes[‘Etisalat’]
KeyError: ‘Etisalat’
>> print Codes unordered 27
{‘Vodafone’: ‘010’, ‘Mobinil’: ‘012’}
• Note: A key can appear at most once in a dictionary (Unique)
Tuples and Dictionaries
• The items() method in dictionaries returns a list of
(key, value) tuples
>>> d = dict()
>>> d[‘id'] = 1002
>>> d[‘name'] = ‘Ali’
>>> for (k,v) in d.items():
print (k, v)
id 1002
name Ali
>>> tups = d.items()
28
>>> print (tups)
[(‘id’, 1002), (‘name’, ‘Ali’)]
Adding and Deleting Items
• To add an item to a Dictionary, assign a value to a
key
>> Codes[‘Etisalat’] = ‘011’
>> print Codes
{‘Vodafone’: ‘010’, ‘Etisalat’: ‘011’, ‘Mobinil’: ‘012’}
Note: if the key already exists its value is replaced
• To delete an Item from a Dictionary use del
>> del Codes[‘Vodafone’]
>> print Codes 29
{‘Etisalat’: ‘011’, ‘Mobinil’: ‘012’}
Modifying Dictionary
personal = { 'fname' : 'Durgesh', 'lname' :
'Samariya', 'age' : 28 }
print(personal) # output
# {'fname': 'Durgesh', 'lname': 'Samariya', 'age':
28}
# change fname and lname
personal['fname'] = 'Hello'
personal['lname'] = 'World'
# output
# {'fname': 'Hello', 'lname': 'World', 'age': 28}

# add city as key and Melbourne as value


personal['city'] = 'Melbourne'
30
# output
# {'fname': 'Hello', 'lname': 'World', 'age': 28, 'city':
'Melbourne'}
Removing key-value from
Dictionary
personal = { 'fname' : 'Durgesh', 'lname' :
'Samariya', 'age' : 28, 'city':'Melbourne'}

print(personal)
# output
# {'fname': 'Durgesh', 'lname': 'Samariya',
'age': 28, 'city':'Melbourne'}

# remove city information


del personal['city']
# output
31
# {'fname': 'Durgesh', 'lname': 'Samariya',
'age': 28}
Looping in Dictionaries
personal = { 'fname' : 'Durgesh', 'lname'
: 'Samariya', 'age' : 28,
'city':'Melbourne'}
# output
for p in personal : # Durgesh
print(personal[p]) # Samariya
# 28
# Melbourne
• If you use a Dictionary in a for statement, it
traverses the keys of the dictionary
32
Dictionary Operations
• keys
• Returns the dictionary’s keys as a list. Entries
are guaranteed to be unique.
>> print ( list( Codes.keys() ))
['Mobinil', 'Etisalat', 'Vodafone']
• values
• Returns the dictionary’s values as a list. Entries
may or may not be unique.
>> print ( list( Codes.values() )) 33
['012', '011', '010']
Ex.
personal = { 'fname' : 'Durgesh', 'lname' :
'Samariya', 'age' : 28 }
# output
for key in personal.keys(): # fname
print(key) # lname
# age

# 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

{'Cairo': '02', 'Mobinil': '012', 'Alex': '03', 'Etisalat':


Example
personal = { 'fname' : 'Durgesh', 'lname' :
'Samariya', 'age' : 28 }
person0 = { 'fname' : ‘Nouh', 'lname' : 'Sara', 'age’
: personal.update(person0)
20 }

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

# {'name': 'Person3', 'age': 40}


create lists in dictionaries

person = {'name':['Durgesh', 'Samariya'], 'age':


27}

# 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

You might also like