SlideShare a Scribd company logo
COSC 1306—COMPUTER
SCIENCE AND PROGRAMMING
PYTHON TUPLES, SETS
AND DICTIONARIES
Jehan-François Pâris
jfparis@uh.edu
TUPLES
Tuples
• Same as lists but
– Immutable
– Enclosed in parentheses
– A tuple with a single element must have a
comma inside the parentheses:
• a = (11,)
Examples
• >>> mytuple = (11, 22, 33)
• >>> mytuple[0]
11
• >>> mytuple[-1]
33
• >>> mytuple[0:1]
(11,)
• The comma is required!
Why?
• No confusion possible between [11] and 11
• (11) is a perfectly acceptable expression
– (11) without the comma is the integer 11
– (11, ) with the comma is a list containing the
integer 11
• Sole dirty trick played on us by tuples!
Tuples are immutable
• >>> mytuple = (11, 22, 33)
• >>> saved = mytuple
• >>> mytuple += (44,)
• >>> mytuple
(11, 22, 33, 44)
• >>> saved
(11, 22, 33)
Things that do not work
• mytuple += 55
Traceback (most recent call last):Z
…
TypeError:
can only concatenate tuple (not "int") to tuple
– Can understand that!
Sorting tuples
• >>> atuple = (33, 22, 11)
• >>> atuple.sort()
Traceback (most recent call last):
…
AttributeError:
'tuple' object has no attribute 'sort'
• >>> atuple = sorted(atuple)
• >>> atuple
[11, 22, 33]
Tuples are immutable!
sorted( ) returns a list!
Most other things work!
• >>> atuple = (11, 22, 33)
• >>> len(atuple)
3
• >>> 44 in atuple
False
• >>> [ i for [i for i in atuple]
[11, 22, 33]
The reverse does not work
• >>> alist = [11, 22, 33]
• >>> (i for i in alist)
<generator object <genexpr> at 0x02855DA0>
– Does not work!
Converting sequences into tuples
• >>> alist = [11, 22, 33]
• >>> atuple = tuple(alist)
• >>> atuple
(11, 22, 33)
• >>> newtuple = tuple('Hello World!')
• >>> newtuple
('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!')
SETS
Sets
• Indentified by curly braces
– {'Alice', 'Bob', 'Carol'}
– {'Dean'} is a singleton
• Can only contain unique elements
– Duplicates are eliminated
• Immutable like tuples and strings
Sets do not contain duplicates
• >>> cset = {11, 11, 22}
• >>> cset
{11, 22}
Sets are immutable
• >>> aset = {11, 22, 33}
• >>> bset = aset
• >>> aset = aset | {55}
• >>> aset
{33, 11, 22, 55}
• >>> bset
{33, 11, 22}
Union of
two sets
Sets have no order
• >>> {1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7}
• >>> {11, 22, 33}
{33, 11, 22}
Sets do not support indexing
• >>> myset = {'Apples', 'Bananas', 'Oranges'}
• >>> myset
{'Bananas', 'Oranges', 'Apples'}
• >>> myset[0]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
myset[0]
TypeError: 'set' object does not support indexing
Examples
• >>> alist = [11, 22, 33, 22, 44]
• >>> aset = set(alist)
• >>> aset
{33, 11, 44, 22}
• >>> aset = aset + {55}
SyntaxError: invalid syntax
Boolean operations on sets (I)
• Union of two sets
• Contains all elements that are in set A or in set B
A B
Boolean operations on sets (II)
• Intersection of two sets
• Contains all elements that are in both sets A and B
A B
Boolean operations on sets (III)
• Difference of two sets
• Contains all elements that are in A but not in B
A B
Boolean operations on sets (IV)
• Symmetric difference of two sets
• Contains all elements that are either
– in set A but not in set B or
– in set B but not in set A
A B
Boolean operations on sets (V)
• >>> aset = {11, 22, 33}
• >>> bset = {12, 23, 33}
• Union of two sets
– >>> aset | bset
{33, 22, 23, 11, 12}
• Intersection of two sets:
– >>> aset & bset
{33}
Boolean operations on sets (VI)
• >>> aset = {11, 22, 33}
• >>> bset = {12, 23, 33}
• Difference:
– >>> aset – bset
{11, 22}
• Symmetric difference:
– >>> aset ^ bset
{11, 12, 22, 23}
DICTIONARIES
Very useful!
Dictionaries (I)
• Store pairs of entries called items
{ 'CS' : '743-713-3350', 'UHPD' : '713-743-3333'}
• Each pair of entries contains
– A key
– A value
• Key and values are separated by a colon
• Paris of entries are separated by commas
• Dictionary is enclosed within curly braces
Usage
• Keys must be unique within a dictionary
– No duplicates
• If we have
age = {'Alice' : 25, 'Bob' :28}
then
age['Alice'] is 25
and
age[Bob'] is 28
Dictionaries are mutable
• >>> age = {'Alice' : 25, 'Bob' : 28}
• >>> saved = age
• >>> age['Bob'] = 29
• >>> age
{'Bob': 29, 'Alice': 25}
• >>> saved
{'Bob': 29, 'Alice': 25}
Keys must be unique
• >>> age = {'Alice' : 25, 'Bob' : 28, 'Alice' : 26}
• >>> age
{'Bob': 28, 'Alice': 26}
Displaying contents
• >>> age = {'Alice' : 25, 'Carol': 'twenty-two'}
• >>> age.items()
dict_items([ ('Alice', 25), ('Carol', 'twenty-two')])
• >>> age.keys()
dict_keys([ 'Alice', 'Carol'])
• age.values()
dict_values([28, 25, 'twenty-two'])
Updating directories
• >>> age = {'Alice': 26 , 'Carol' : 22}
• >>> age.update({'Bob' : 29})
• >>> age
{'Bob': 29, 'Carol': 22, 'Alice': 26}
• >>> age.update({'Carol' : 23})
• >>> age
{'Bob': 29, 'Carol': 23, 'Alice': 26}
Returning a value
• >>> age = {'Bob': 29, 'Carol': 23, 'Alice': 26}
• >>> age.get('Bob')
29
• >>> age['Bob']
29
Removing a specific item (I)
• >>> a = {'Alice' : 26, 'Carol' : 'twenty-two'}
• >>> a
{'Carol': 'twenty-two', 'Alice': 26}
• >>> a.pop('Carol’)
'twenty-two'
• >>> a
{'Alice': 26}
Removing a specific item (II)
• >>> a.pop('Alice')
26
• >>> a
{}
• >>>
Remove a random item
• >>> age = {'Bob': 29, 'Carol': 23, 'Alice': 26}
• >>> age.popitem()
('Bob', 29)
• >>> age
• {'Carol': 23, 'Alice': 26}
• >>> age.popitem()
('Carol', 23)
• >>> age
{'Alice': 26}
Summary
• Strings, lists, tuples, sets and dictionaries all
deal with aggregates
• Two big differences
– Lists and dictionaries are mutable
• Unlike strings, tuples and sets
– Strings, lists and tuples are ordered
• Unlike sets and dictionaries
Mutable aggregates
• Can modify individual items
– x = [11, 22, 33]
x[0] = 44
will work
• Cannot save current value
– x = [11,22, 33]
y = x
will not work
Immutable aggregates
• Cannot modify individual items
– s = 'hello!'
s[0] = 'H'
is an ERROR
• Can save current value
– s= 'hello!'
t = s
will work
Ordered aggregates
• Entities in the collection can be accessed through a
numerical index
– s= 'Hello!'
s[0]
– x = ['Alice', 'Bob', 'Carol']
x[-1]
– t = (11, 22)
t[1]
Other aggregates
• Cannot index sets
– myset = {'Apples', 'Bananas', 'Oranges'}
myset[0] is WRONG
• Can only index dictionaries through their keys
– age = {'Bob': 29, 'Carol': 23, 'Alice': 26}
age['Alice'] works
age[0] is WRONG

More Related Content

PPT
Tuples, sets angsdfgsfdgdfgfdgd dictionaries 2.ppt
PPT
Introduction to set theory with application
PPT
SetTheory.ppt
PPT
SetTheory.ppt
PPT
1. set theory
PPT
A set is a structure, representing an unordered collection (group, plurality)...
PDF
Digital Electronics
PPTX
introduction to set theory and logic theory.pptx
Tuples, sets angsdfgsfdgdfgfdgd dictionaries 2.ppt
Introduction to set theory with application
SetTheory.ppt
SetTheory.ppt
1. set theory
A set is a structure, representing an unordered collection (group, plurality)...
Digital Electronics
introduction to set theory and logic theory.pptx

Recently uploaded (20)

PDF
PPT on Performance Review to get promotions
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Geodesy 1.pptx...............................................
PPTX
OOP with Java - Java Introduction (Basics)
DOCX
573137875-Attendance-Management-System-original
PDF
composite construction of structures.pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Lecture Notes Electrical Wiring System Components
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
web development for engineering and engineering
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPT on Performance Review to get promotions
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Operating System & Kernel Study Guide-1 - converted.pdf
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
additive manufacturing of ss316l using mig welding
Geodesy 1.pptx...............................................
OOP with Java - Java Introduction (Basics)
573137875-Attendance-Management-System-original
composite construction of structures.pdf
CH1 Production IntroductoryConcepts.pptx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Model Code of Practice - Construction Work - 21102022 .pdf
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Lecture Notes Electrical Wiring System Components
R24 SURVEYING LAB MANUAL for civil enggi
web development for engineering and engineering
CYBER-CRIMES AND SECURITY A guide to understanding
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Ad
Ad

Tuples, sets and dictionaries-Programming in Python

  • 1. COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON TUPLES, SETS AND DICTIONARIES Jehan-François Pâris jfparis@uh.edu
  • 3. Tuples • Same as lists but – Immutable – Enclosed in parentheses – A tuple with a single element must have a comma inside the parentheses: • a = (11,)
  • 4. Examples • >>> mytuple = (11, 22, 33) • >>> mytuple[0] 11 • >>> mytuple[-1] 33 • >>> mytuple[0:1] (11,) • The comma is required!
  • 5. Why? • No confusion possible between [11] and 11 • (11) is a perfectly acceptable expression – (11) without the comma is the integer 11 – (11, ) with the comma is a list containing the integer 11 • Sole dirty trick played on us by tuples!
  • 6. Tuples are immutable • >>> mytuple = (11, 22, 33) • >>> saved = mytuple • >>> mytuple += (44,) • >>> mytuple (11, 22, 33, 44) • >>> saved (11, 22, 33)
  • 7. Things that do not work • mytuple += 55 Traceback (most recent call last):Z … TypeError: can only concatenate tuple (not "int") to tuple – Can understand that!
  • 8. Sorting tuples • >>> atuple = (33, 22, 11) • >>> atuple.sort() Traceback (most recent call last): … AttributeError: 'tuple' object has no attribute 'sort' • >>> atuple = sorted(atuple) • >>> atuple [11, 22, 33] Tuples are immutable! sorted( ) returns a list!
  • 9. Most other things work! • >>> atuple = (11, 22, 33) • >>> len(atuple) 3 • >>> 44 in atuple False • >>> [ i for [i for i in atuple] [11, 22, 33]
  • 10. The reverse does not work • >>> alist = [11, 22, 33] • >>> (i for i in alist) <generator object <genexpr> at 0x02855DA0> – Does not work!
  • 11. Converting sequences into tuples • >>> alist = [11, 22, 33] • >>> atuple = tuple(alist) • >>> atuple (11, 22, 33) • >>> newtuple = tuple('Hello World!') • >>> newtuple ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!')
  • 12. SETS
  • 13. Sets • Indentified by curly braces – {'Alice', 'Bob', 'Carol'} – {'Dean'} is a singleton • Can only contain unique elements – Duplicates are eliminated • Immutable like tuples and strings
  • 14. Sets do not contain duplicates • >>> cset = {11, 11, 22} • >>> cset {11, 22}
  • 15. Sets are immutable • >>> aset = {11, 22, 33} • >>> bset = aset • >>> aset = aset | {55} • >>> aset {33, 11, 22, 55} • >>> bset {33, 11, 22} Union of two sets
  • 16. Sets have no order • >>> {1, 2, 3, 4, 5, 6, 7} {1, 2, 3, 4, 5, 6, 7} • >>> {11, 22, 33} {33, 11, 22}
  • 17. Sets do not support indexing • >>> myset = {'Apples', 'Bananas', 'Oranges'} • >>> myset {'Bananas', 'Oranges', 'Apples'} • >>> myset[0] Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> myset[0] TypeError: 'set' object does not support indexing
  • 18. Examples • >>> alist = [11, 22, 33, 22, 44] • >>> aset = set(alist) • >>> aset {33, 11, 44, 22} • >>> aset = aset + {55} SyntaxError: invalid syntax
  • 19. Boolean operations on sets (I) • Union of two sets • Contains all elements that are in set A or in set B A B
  • 20. Boolean operations on sets (II) • Intersection of two sets • Contains all elements that are in both sets A and B A B
  • 21. Boolean operations on sets (III) • Difference of two sets • Contains all elements that are in A but not in B A B
  • 22. Boolean operations on sets (IV) • Symmetric difference of two sets • Contains all elements that are either – in set A but not in set B or – in set B but not in set A A B
  • 23. Boolean operations on sets (V) • >>> aset = {11, 22, 33} • >>> bset = {12, 23, 33} • Union of two sets – >>> aset | bset {33, 22, 23, 11, 12} • Intersection of two sets: – >>> aset & bset {33}
  • 24. Boolean operations on sets (VI) • >>> aset = {11, 22, 33} • >>> bset = {12, 23, 33} • Difference: – >>> aset – bset {11, 22} • Symmetric difference: – >>> aset ^ bset {11, 12, 22, 23}
  • 26. Dictionaries (I) • Store pairs of entries called items { 'CS' : '743-713-3350', 'UHPD' : '713-743-3333'} • Each pair of entries contains – A key – A value • Key and values are separated by a colon • Paris of entries are separated by commas • Dictionary is enclosed within curly braces
  • 27. Usage • Keys must be unique within a dictionary – No duplicates • If we have age = {'Alice' : 25, 'Bob' :28} then age['Alice'] is 25 and age[Bob'] is 28
  • 28. Dictionaries are mutable • >>> age = {'Alice' : 25, 'Bob' : 28} • >>> saved = age • >>> age['Bob'] = 29 • >>> age {'Bob': 29, 'Alice': 25} • >>> saved {'Bob': 29, 'Alice': 25}
  • 29. Keys must be unique • >>> age = {'Alice' : 25, 'Bob' : 28, 'Alice' : 26} • >>> age {'Bob': 28, 'Alice': 26}
  • 30. Displaying contents • >>> age = {'Alice' : 25, 'Carol': 'twenty-two'} • >>> age.items() dict_items([ ('Alice', 25), ('Carol', 'twenty-two')]) • >>> age.keys() dict_keys([ 'Alice', 'Carol']) • age.values() dict_values([28, 25, 'twenty-two'])
  • 31. Updating directories • >>> age = {'Alice': 26 , 'Carol' : 22} • >>> age.update({'Bob' : 29}) • >>> age {'Bob': 29, 'Carol': 22, 'Alice': 26} • >>> age.update({'Carol' : 23}) • >>> age {'Bob': 29, 'Carol': 23, 'Alice': 26}
  • 32. Returning a value • >>> age = {'Bob': 29, 'Carol': 23, 'Alice': 26} • >>> age.get('Bob') 29 • >>> age['Bob'] 29
  • 33. Removing a specific item (I) • >>> a = {'Alice' : 26, 'Carol' : 'twenty-two'} • >>> a {'Carol': 'twenty-two', 'Alice': 26} • >>> a.pop('Carol’) 'twenty-two' • >>> a {'Alice': 26}
  • 34. Removing a specific item (II) • >>> a.pop('Alice') 26 • >>> a {} • >>>
  • 35. Remove a random item • >>> age = {'Bob': 29, 'Carol': 23, 'Alice': 26} • >>> age.popitem() ('Bob', 29) • >>> age • {'Carol': 23, 'Alice': 26} • >>> age.popitem() ('Carol', 23) • >>> age {'Alice': 26}
  • 36. Summary • Strings, lists, tuples, sets and dictionaries all deal with aggregates • Two big differences – Lists and dictionaries are mutable • Unlike strings, tuples and sets – Strings, lists and tuples are ordered • Unlike sets and dictionaries
  • 37. Mutable aggregates • Can modify individual items – x = [11, 22, 33] x[0] = 44 will work • Cannot save current value – x = [11,22, 33] y = x will not work
  • 38. Immutable aggregates • Cannot modify individual items – s = 'hello!' s[0] = 'H' is an ERROR • Can save current value – s= 'hello!' t = s will work
  • 39. Ordered aggregates • Entities in the collection can be accessed through a numerical index – s= 'Hello!' s[0] – x = ['Alice', 'Bob', 'Carol'] x[-1] – t = (11, 22) t[1]
  • 40. Other aggregates • Cannot index sets – myset = {'Apples', 'Bananas', 'Oranges'} myset[0] is WRONG • Can only index dictionaries through their keys – age = {'Bob': 29, 'Carol': 23, 'Alice': 26} age['Alice'] works age[0] is WRONG