SlideShare a Scribd company logo
7. Tuples
1ARULKUMAR V AP/CSE SECE
Motivations
The No Fly List is a list, created and maintained by
the United States government's Terrorist Screening
Center, of people who are not permitted to board
a commercial aircraft for travel in or out of the
United States. Suppose we need to write a
program that checks whether a person is in the No
Fly List. You can use a Python list to store the
persons in the No Fly List. However, a more
efficient data structure for this application is a set.
2ARULKUMAR V AP/CSE SECE
Objectives
• To use tuples as immutable lists (§14.2).
• To use sets for storing and fast accessing non-
duplicate elements (§14.3).
• To understand the performance differences
between sets and lists (§14.4).
• To store key/value pairs in a dictionary and
access value using the key (§14.5).
• To use dictionaries to develop applications
(§14.6).
3ARULKUMAR V AP/CSE SECE
Tuples
4
Tuples are like lists except they are immutable.
Once they are created, their contents cannot be
changed.
If the contents of a list in your application do not
change, you should use a tuple to prevent data from
being modified accidentally. Furthermore, tuples are
more efficient than lists.
ARULKUMAR V AP/CSE SECE
Creating Tuples
5
t1 = () # Create an empty tuple
t2 = (1, 3, 5) # Create a set with three elements
# Create a tuple from a list
t3 = tuple([2 * x for x in range(1, 5)])
# Create a tuple from a string
t4 = tuple("abac") # t4 is ['a', 'b', 'a', 'c']
ARULKUMAR V AP/CSE SECE
Tuples
6
Tuples can be used like lists except they are
immutable.
TupleDemo Run
ARULKUMAR V AP/CSE SECE
Sets
7
Sets are like lists to store a collection of items.
Unlike lists, the elements in a set are unique and
are not placed in any particular ordered. If your
application does not care about the order of the
elements, using a set to store elements is more
efficient than using lists. The syntax for sets is
braces {}.
ARULKUMAR V AP/CSE SECE
Creating Sets
8
s1 = set() # Create an empty set
s2 = {1, 3, 5} # Create a set with three elements
s3 = set([1, 3, 5]) # Create a set from a tuple
# Create a set from a list
s4 = set([x * 2 for x in range(1, 10)])
# Create a set from a string
s5 = set("abac") # s5 is {'a', 'b', 'c'}
ARULKUMAR V AP/CSE SECE
Manipulating and Accessing Sets
9
>>> s1 = {1, 2, 4}
>>> s1.add(6)
>>> s1
{1, 2, 4, 6}
>>> len(s1)
4
>>> max(s1)
6
>>> min(s1)
1
>>> sum(s1)
13
>>> 3 in s1
False
>>> s1.remove(4)
>>> s1
{1, 2, 6}
>>>
ARULKUMAR V AP/CSE SECE
Subset and Superset
10
>>> s1 = {1, 2, 4}
>>> s2 = {1, 4, 5, 2, 6}
>>> s1.issubset(s2) # s1 is a subset of s2
True
>>>
>>> s1 = {1, 2, 4}
>>> s2 = {1, 4, 5, 2, 6}
>>> s2.issuperset(s1) # s2 is a superset of
s1
True
>>>
ARULKUMAR V AP/CSE SECE
Equality Test
11
>>> s1 = {1, 2, 4}
>>> s2 = {1, 4, 2}
>>> s1 == s2
True
>>> s1 != s2
False
>>>
ARULKUMAR V AP/CSE SECE
Comparison Operators
12
Note that it makes no sense to compare the sets using the
conventional comparison operators (>, >=, <=, <), because
the elements in a set are not ordered. However, these
operators have special meaning when used for sets.
s1 > s2 returns true is s1 is a proper superset of s2.
s1 >= s2 returns true is s1 is a superset of s2.
s1 < s2 returns true is s1 is a proper subset of s2.
s1 <= s2 returns true is s1 is a subset of s2.
ARULKUMAR V AP/CSE SECE
Set Operations (union, |)
13
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.union(s2)
{1, 2, 3, 4, 5}
>>>
>>> s1 | s2
{1, 2, 3, 4, 5}
>>>
ARULKUMAR V AP/CSE SECE
Set Operations (intersection, &)
14
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.intersection(s2)
{1}
>>>
>>> s1 & s2
{1}
>>>
ARULKUMAR V AP/CSE SECE
Set Operations (difference, -)
15
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.difference(s2)
{2, 4}
>>>
>>> s1 - s2
{2, 4}
>>>
ARULKUMAR V AP/CSE SECE
Set Operations
(symetric_difference, ^)
16
>>> s1 = {1, 2, 4}
>>> s2 = {1, 3, 5}
>>> s1.symmetric_difference(s2)
{2, 3, 4, 5}
>>>
>>> s1 ^ s2
{2, 3, 4, 5}
>>>
ARULKUMAR V AP/CSE SECE
Sets
17
SetDemo Run
ARULKUMAR V AP/CSE SECE
Comparing Performance of Sets and
Lists
18
SetListPerformanceTest Run
ARULKUMAR V AP/CSE SECE
Dictionary
Why dictionary?
Suppose your program stores a million students
and frequently searches for a student using the
social security number. An efficient data
structure for this task is the dictionary. A
dictionary is a collection that stores the
elements along with the keys. The keys are like
an indexer.
19ARULKUMAR V AP/CSE SECE
Key/value pairs
20
Search keys Corresponding element values
…
.
.
Entry
A dictionary
ARULKUMAR V AP/CSE SECE
Creating a Dictionary
dictionary = {} # Create an empty dictionary
dictionary = {"john":40, "peter":45} # Create a dictionary
21ARULKUMAR V AP/CSE SECE
Adding/Modifying Entries
To add an entry to a dictionary, use
dictionary[key] = value
For example,
dictionary["susan"] = 50
22ARULKUMAR V AP/CSE SECE
Deleting Entries
To delete an entry from a dictionary, use
del dictionary[key]
For example,
del dictionary["susan"]
23ARULKUMAR V AP/CSE SECE
Looping Entries
for key in dictionary:
print(key + ":" + str(dictionary[key]))
24ARULKUMAR V AP/CSE SECE
The len and in operators
len(dictionary) returns the number of the
elements in the dictionary.
25
>>> dictionary = {"john":40, "peter":45}
>>> "john" in dictionary
True
>>> "johnson" in dictionary
False
ARULKUMAR V AP/CSE SECE
The Dictionary Methods
26
dict
keys(): tuple
values(): tuple
items(): tuple
clear(): void
get(key): value
pop(key): value
popitem(): tuple
Returns a sequence of keys.
Returns a sequence of values.
Returns a sequence of tuples (key, value).
Deletes all entries.
Returns the value for the key.
Removes the entry for the key and returns its value.
Returns a randomly-selected key/value pair as a tuple and
removes the selected entry.
ARULKUMAR V AP/CSE SECE
Case Studies: Occurrences of Words
27
Run
This case study writes a program that counts the
occurrences of words in a text file and displays the words
and their occurrences in alphabetical order of words. The
program uses a dictionary to store an entry consisting of a
word and its count. For each word, check whether it is
already a key in the dictionary. If not, add to the dictionary
an entry with the word as the key and value 1. Otherwise,
increase the value for the word (key) by 1 in the dictionary.
CountOccurrenceOfWords
ARULKUMAR V AP/CSE SECE

More Related Content

What's hot

Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variables
sana mateen
 
MYSQL
MYSQLMYSQL
MYSQL
ARJUN
 
Sql Tags
Sql TagsSql Tags
Les10
Les10Les10
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Php array
Php arrayPhp array
Php array
Core Lee
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
Ahmed Swilam
 
Sets
SetsSets
My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax
Reka
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト
Opt Technologies
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries
Prabu Cse
 
Arrays in PHP
Arrays in PHPArrays in PHP
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
channa basava
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
Samuel Lampa
 
Php array
Php arrayPhp array
Php array
Nikul Shah
 
Obtain better data accuracy using reference tables
Obtain better data accuracy using reference tablesObtain better data accuracy using reference tables
Obtain better data accuracy using reference tables
Kiran Venna
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
Vamshi Santhapuri
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
Balqees Al.Mubarak
 
R part iii
R part iiiR part iii
R part iii
Ruru Chowdhury
 

What's hot (19)

Perl names values and variables
Perl names values and variablesPerl names values and variables
Perl names values and variables
 
MYSQL
MYSQLMYSQL
MYSQL
 
Sql Tags
Sql TagsSql Tags
Sql Tags
 
Les10
Les10Les10
Les10
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Php array
Php arrayPhp array
Php array
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Sets
SetsSets
Sets
 
My sql Syntax
My sql SyntaxMy sql Syntax
My sql Syntax
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト
 
Prabu's sql quries
Prabu's sql quries Prabu's sql quries
Prabu's sql quries
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
iRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat SheetiRODS Rule Language Cheat Sheet
iRODS Rule Language Cheat Sheet
 
Php array
Php arrayPhp array
Php array
 
Obtain better data accuracy using reference tables
Obtain better data accuracy using reference tablesObtain better data accuracy using reference tables
Obtain better data accuracy using reference tables
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
 
Lab5 sub query
Lab5   sub queryLab5   sub query
Lab5 sub query
 
R part iii
R part iiiR part iii
R part iii
 

Similar to 7. tuples, set &amp; dictionary

5. string
5. string5. string
SQL Tutorial for Beginners
SQL Tutorial for BeginnersSQL Tutorial for Beginners
SQL Tutorial for Beginners
Abdelhay Shafi
 
SQL Query
SQL QuerySQL Query
SQL Query
Imam340267
 
SQL
SQLSQL
Les13
Les13Les13
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
amitabros
 
Mysql1
Mysql1Mysql1
Mysql1
rajikaa
 
Lists and arrays
Lists and arraysLists and arrays
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
Abhishek590097
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Eelco Visser
 
98765432345671223Intro-to-PostgreSQL.ppt
98765432345671223Intro-to-PostgreSQL.ppt98765432345671223Intro-to-PostgreSQL.ppt
98765432345671223Intro-to-PostgreSQL.ppt
HastavaramDineshKuma
 
Set relationship, set operation and sigmoid
Set relationship, set operation and sigmoidSet relationship, set operation and sigmoid
Set relationship, set operation and sigmoid
Kanza batool
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
PriyaPandey767008
 
ADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASADADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASAD
PADYALAMAITHILINATHA
 
2. data types, variables and operators
2. data types, variables and operators2. data types, variables and operators
2. data types, variables and operators
PhD Research Scholar
 
Sql slid
Sql slidSql slid
Sql slid
pacatarpit
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
Vaibhav Kathuria
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
Dave Cross
 
Sql Document in Testing
Sql Document in TestingSql Document in Testing
Sql Document in Testing
Saurabh Bhardwaj
 
SQL
SQLSQL

Similar to 7. tuples, set &amp; dictionary (20)

5. string
5. string5. string
5. string
 
SQL Tutorial for Beginners
SQL Tutorial for BeginnersSQL Tutorial for Beginners
SQL Tutorial for Beginners
 
SQL Query
SQL QuerySQL Query
SQL Query
 
SQL
SQLSQL
SQL
 
Les13
Les13Les13
Les13
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Mysql1
Mysql1Mysql1
Mysql1
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQueryPPT  of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
PPT of Common Table Expression (CTE), Window Functions, JOINS, SubQuery
 
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term RewritingCompiler Construction | Lecture 5 | Transformation by Term Rewriting
Compiler Construction | Lecture 5 | Transformation by Term Rewriting
 
98765432345671223Intro-to-PostgreSQL.ppt
98765432345671223Intro-to-PostgreSQL.ppt98765432345671223Intro-to-PostgreSQL.ppt
98765432345671223Intro-to-PostgreSQL.ppt
 
Set relationship, set operation and sigmoid
Set relationship, set operation and sigmoidSet relationship, set operation and sigmoid
Set relationship, set operation and sigmoid
 
SQL PPT.pptx
SQL PPT.pptxSQL PPT.pptx
SQL PPT.pptx
 
ADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASADADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASAD
 
2. data types, variables and operators
2. data types, variables and operators2. data types, variables and operators
2. data types, variables and operators
 
Sql slid
Sql slidSql slid
Sql slid
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Intermediate Perl
Intermediate PerlIntermediate Perl
Intermediate Perl
 
Sql Document in Testing
Sql Document in TestingSql Document in Testing
Sql Document in Testing
 
SQL
SQLSQL
SQL
 

More from PhD Research Scholar

Ajax
AjaxAjax
Quiz servlet
Quiz servletQuiz servlet
Quiz servlet
PhD Research Scholar
 
Quiz
QuizQuiz
servlet db connectivity
servlet db connectivityservlet db connectivity
servlet db connectivity
PhD Research Scholar
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom
PhD Research Scholar
 
1.java script
1.java script1.java script
1.java script
PhD Research Scholar
 
Quiz javascript
Quiz javascriptQuiz javascript
Quiz javascript
PhD Research Scholar
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread
PhD Research Scholar
 
String
StringString
Streams&amp;io
Streams&amp;ioStreams&amp;io
Streams&amp;io
PhD Research Scholar
 
Packages
PackagesPackages
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 
Inheritance
InheritanceInheritance
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Applets
AppletsApplets
Abstract class
Abstract classAbstract class
Abstract class
PhD Research Scholar
 
4. functions
4. functions4. functions
4. functions
PhD Research Scholar
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement
PhD Research Scholar
 
3.1 conditional statement
3.1 conditional statement3.1 conditional statement
3.1 conditional statement
PhD Research Scholar
 

More from PhD Research Scholar (20)

Ajax
AjaxAjax
Ajax
 
Quiz servlet
Quiz servletQuiz servlet
Quiz servlet
 
Quiz
QuizQuiz
Quiz
 
servlet db connectivity
servlet db connectivityservlet db connectivity
servlet db connectivity
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom
 
1.java script
1.java script1.java script
1.java script
 
Quiz javascript
Quiz javascriptQuiz javascript
Quiz javascript
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread
 
String
StringString
String
 
Streams&amp;io
Streams&amp;ioStreams&amp;io
Streams&amp;io
 
Packages
PackagesPackages
Packages
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Exception handling
Exception handlingException handling
Exception handling
 
Applets
AppletsApplets
Applets
 
Abstract class
Abstract classAbstract class
Abstract class
 
4. functions
4. functions4. functions
4. functions
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement
 
3.1 conditional statement
3.1 conditional statement3.1 conditional statement
3.1 conditional statement
 

Recently uploaded

writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
spdendr
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 

Recently uploaded (20)

writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 

7. tuples, set &amp; dictionary

  • 2. Motivations The No Fly List is a list, created and maintained by the United States government's Terrorist Screening Center, of people who are not permitted to board a commercial aircraft for travel in or out of the United States. Suppose we need to write a program that checks whether a person is in the No Fly List. You can use a Python list to store the persons in the No Fly List. However, a more efficient data structure for this application is a set. 2ARULKUMAR V AP/CSE SECE
  • 3. Objectives • To use tuples as immutable lists (§14.2). • To use sets for storing and fast accessing non- duplicate elements (§14.3). • To understand the performance differences between sets and lists (§14.4). • To store key/value pairs in a dictionary and access value using the key (§14.5). • To use dictionaries to develop applications (§14.6). 3ARULKUMAR V AP/CSE SECE
  • 4. Tuples 4 Tuples are like lists except they are immutable. Once they are created, their contents cannot be changed. If the contents of a list in your application do not change, you should use a tuple to prevent data from being modified accidentally. Furthermore, tuples are more efficient than lists. ARULKUMAR V AP/CSE SECE
  • 5. Creating Tuples 5 t1 = () # Create an empty tuple t2 = (1, 3, 5) # Create a set with three elements # Create a tuple from a list t3 = tuple([2 * x for x in range(1, 5)]) # Create a tuple from a string t4 = tuple("abac") # t4 is ['a', 'b', 'a', 'c'] ARULKUMAR V AP/CSE SECE
  • 6. Tuples 6 Tuples can be used like lists except they are immutable. TupleDemo Run ARULKUMAR V AP/CSE SECE
  • 7. Sets 7 Sets are like lists to store a collection of items. Unlike lists, the elements in a set are unique and are not placed in any particular ordered. If your application does not care about the order of the elements, using a set to store elements is more efficient than using lists. The syntax for sets is braces {}. ARULKUMAR V AP/CSE SECE
  • 8. Creating Sets 8 s1 = set() # Create an empty set s2 = {1, 3, 5} # Create a set with three elements s3 = set([1, 3, 5]) # Create a set from a tuple # Create a set from a list s4 = set([x * 2 for x in range(1, 10)]) # Create a set from a string s5 = set("abac") # s5 is {'a', 'b', 'c'} ARULKUMAR V AP/CSE SECE
  • 9. Manipulating and Accessing Sets 9 >>> s1 = {1, 2, 4} >>> s1.add(6) >>> s1 {1, 2, 4, 6} >>> len(s1) 4 >>> max(s1) 6 >>> min(s1) 1 >>> sum(s1) 13 >>> 3 in s1 False >>> s1.remove(4) >>> s1 {1, 2, 6} >>> ARULKUMAR V AP/CSE SECE
  • 10. Subset and Superset 10 >>> s1 = {1, 2, 4} >>> s2 = {1, 4, 5, 2, 6} >>> s1.issubset(s2) # s1 is a subset of s2 True >>> >>> s1 = {1, 2, 4} >>> s2 = {1, 4, 5, 2, 6} >>> s2.issuperset(s1) # s2 is a superset of s1 True >>> ARULKUMAR V AP/CSE SECE
  • 11. Equality Test 11 >>> s1 = {1, 2, 4} >>> s2 = {1, 4, 2} >>> s1 == s2 True >>> s1 != s2 False >>> ARULKUMAR V AP/CSE SECE
  • 12. Comparison Operators 12 Note that it makes no sense to compare the sets using the conventional comparison operators (>, >=, <=, <), because the elements in a set are not ordered. However, these operators have special meaning when used for sets. s1 > s2 returns true is s1 is a proper superset of s2. s1 >= s2 returns true is s1 is a superset of s2. s1 < s2 returns true is s1 is a proper subset of s2. s1 <= s2 returns true is s1 is a subset of s2. ARULKUMAR V AP/CSE SECE
  • 13. Set Operations (union, |) 13 >>> s1 = {1, 2, 4} >>> s2 = {1, 3, 5} >>> s1.union(s2) {1, 2, 3, 4, 5} >>> >>> s1 | s2 {1, 2, 3, 4, 5} >>> ARULKUMAR V AP/CSE SECE
  • 14. Set Operations (intersection, &) 14 >>> s1 = {1, 2, 4} >>> s2 = {1, 3, 5} >>> s1.intersection(s2) {1} >>> >>> s1 & s2 {1} >>> ARULKUMAR V AP/CSE SECE
  • 15. Set Operations (difference, -) 15 >>> s1 = {1, 2, 4} >>> s2 = {1, 3, 5} >>> s1.difference(s2) {2, 4} >>> >>> s1 - s2 {2, 4} >>> ARULKUMAR V AP/CSE SECE
  • 16. Set Operations (symetric_difference, ^) 16 >>> s1 = {1, 2, 4} >>> s2 = {1, 3, 5} >>> s1.symmetric_difference(s2) {2, 3, 4, 5} >>> >>> s1 ^ s2 {2, 3, 4, 5} >>> ARULKUMAR V AP/CSE SECE
  • 18. Comparing Performance of Sets and Lists 18 SetListPerformanceTest Run ARULKUMAR V AP/CSE SECE
  • 19. Dictionary Why dictionary? Suppose your program stores a million students and frequently searches for a student using the social security number. An efficient data structure for this task is the dictionary. A dictionary is a collection that stores the elements along with the keys. The keys are like an indexer. 19ARULKUMAR V AP/CSE SECE
  • 20. Key/value pairs 20 Search keys Corresponding element values … . . Entry A dictionary ARULKUMAR V AP/CSE SECE
  • 21. Creating a Dictionary dictionary = {} # Create an empty dictionary dictionary = {"john":40, "peter":45} # Create a dictionary 21ARULKUMAR V AP/CSE SECE
  • 22. Adding/Modifying Entries To add an entry to a dictionary, use dictionary[key] = value For example, dictionary["susan"] = 50 22ARULKUMAR V AP/CSE SECE
  • 23. Deleting Entries To delete an entry from a dictionary, use del dictionary[key] For example, del dictionary["susan"] 23ARULKUMAR V AP/CSE SECE
  • 24. Looping Entries for key in dictionary: print(key + ":" + str(dictionary[key])) 24ARULKUMAR V AP/CSE SECE
  • 25. The len and in operators len(dictionary) returns the number of the elements in the dictionary. 25 >>> dictionary = {"john":40, "peter":45} >>> "john" in dictionary True >>> "johnson" in dictionary False ARULKUMAR V AP/CSE SECE
  • 26. The Dictionary Methods 26 dict keys(): tuple values(): tuple items(): tuple clear(): void get(key): value pop(key): value popitem(): tuple Returns a sequence of keys. Returns a sequence of values. Returns a sequence of tuples (key, value). Deletes all entries. Returns the value for the key. Removes the entry for the key and returns its value. Returns a randomly-selected key/value pair as a tuple and removes the selected entry. ARULKUMAR V AP/CSE SECE
  • 27. Case Studies: Occurrences of Words 27 Run This case study writes a program that counts the occurrences of words in a text file and displays the words and their occurrences in alphabetical order of words. The program uses a dictionary to store an entry consisting of a word and its count. For each word, check whether it is already a key in the dictionary. If not, add to the dictionary an entry with the word as the key and value 1. Otherwise, increase the value for the word (key) by 1 in the dictionary. CountOccurrenceOfWords ARULKUMAR V AP/CSE SECE