SlideShare ist ein Scribd-Unternehmen logo
1 von 21
15-110: Principles of
Computing
Sequences- Part IV (Tuples and Dictionaries)
Lecture 15, October 23, 2018
Mohammad Hammoud
Carnegie Mellon University in Qatar
Today…
• Last Session:
• Sequences- Part III (Matrix Operations as an Application on Lists)
• Today’s Session:
• Sequences- Part IV:
• Tuples
• Dictionaries
Tuples
• Tuples are very similar to lists, but they are immutable (i.e.,
unchangeable)
• Tuples are written with round brackets as follows:
t1 = (1, 2, 3)
t2 = (“a”, “b”, “c”, ”d”)
t3 = (200, “A”, [4, 5], 3.2)
print(t1)
print(t2)
print(t3)
Tuples
• Like lists, tuples can:
• Contain any and different types of elements
• Contain duplicate elements (e.g., (1, 1, 2))
• Be indexed exactly in the same way (i.e., using the [] brackets)
• Be sliced exactly in the same way (i.e., using the [::] notation)
• Be concatenated (e.g., t = (1, 2, 3) + (“a”, “b”, “c”))
• Be repeated (e.g., t = (“a”, “b”) * 10)
• Be nested (e.g., t = ((1, 2), (3, 4), ((“a”, “b”, ”c”), 3.4))
• Be passed to a function, but will result in pass-by-value and not pass-by-
reference outcome since it is immutable
• Be iterated over
Examples
t1 = ("a", "b", "c")
print(t1[::-1])
t2 = ("a", "b", "c")
t3 = t1 + t2
print(t3)
t3 = t3 * 4
print(t3)
for i in t3:
print(i, end = " ")
print()
This will print the elements of t1 in
a reversed order, but will not change
t1 itself since it is immutable
This will concatenate t1 and t2 and
assign the result to t3 (again, t1 and
t2 will be unchanged since they are
immutable)
This will repeat t3 four times and
assign the result to t3. Hence,
t3 will be overwritten (i.e., NOT
changed in place- because it is
immutable-, but redefined with a
new value)
Examples
t4 = ((1, 2, 3), ("a", "b", "c"))
for j in t4:
for k in j:
print(k,end = " ")
print()
This is an example of nesting, where
a matrix with 2 rows and
3 columns is created. The first row
includes the elements 1, 2, and 3.
The second row includes the elements
“a”, “b”, and “c”.
This outer loop iterates over each
element in t4; that is, it gets first the
element (1, 2, 3) and second the
element (“a”, “b”, “c”)
This inner loop iterates over each
element read by the outer loop; that
is, it first iterates over the elements
of the element (1, 2, 3), and second
it iterates over the elements of the
element (“a”, “b”, “c”)
Examples
def func1(t):
t = t * 2
t = (1, 2, 3)
print(t)
func1(t)
print(t)
This will output (1, 2, 3)
This will also output (1, 2, 3) since
tuples are immutable, hence, will
always exhibit a passed-by-value
behavior
This change on t remains local to the function
since a value of t was passed and not a
reference to it
Using Functions with Tuples
• You can also use functions with tuples
t1 = (1, 2, 3, 1, 5, 1)
print(t1.count(1))
print(t1.index(1))
The count(x) function returns the number of
elements with the specified value x (e.g., x is 1
in this example)
The index(x) function returns the index of the
first element with the specified value x (e.g., x
is 1 in this example)
Output:
3
0
In fact, Python has only these two built-in functions that can be used
on tuples
Towards Dictionaries
• Lists and tuples hold elements with only integer indices
• So in essence, each element has an index (or a key) which can only be
an integer, and a value which can be of any type (e.g., in the above
list/tuple, the first element has key 0 and value 45)
• What if we want to store elements with non-integer indices (or keys)?
45 “Coding” 4.5 7 89
0 1 2 3 4
Integer
Indices
Dictionaries
• In Python, you can use a dictionary to store elements with keys of any
types (not necessarily only integers like lists and tuples) and values of
any types as well
• The above dictionary can be defined in Python as follows:
dic = {"NUM":45, 1000:"coding", 2000:4.5, 3.4:7, "XXX":89}
45 “Coding” 4.5 7 89
“NUM” 1000 2000 3.4 “XXX”
keys of different types
Each element is a key:value pair, and elements are separated by commas
key value
Values of different types
Dictionaries
• In summary, dictionaries:
• Can contain any and different types of elements (i.e., keys and values)
• Can contain only unique keys but duplicate values
• Can be indexed but only through keys (i.e., dic2[“a”] will return 1 but dic2[0]
will return an error since there is no element with key 0 in dic2 above)
Output: {'a': 2, 'b': 2}
dic2 = {"a":1, "a":2, "b":2}
print(dic2)
The element “a”:2 will override the element “a”:1
because only ONE element can have key “a”
Dictionaries
• In summary, dictionaries:
• CANNOT be concatenated
• CANNOT be repeated
• Can be nested (e.g., d = {"first":{1:1}, "second":{2:"a"}}
• Can be passed to a function and will result in a pass-by-reference and not
pass-by-value behavior since it is immutable (like lists)
Output:
{'first': {1: 1}, 'second': {2: 'a'}}
{'first': [1, 2, 3], 'second': {2: 'a'}}
def func1(d):
d["first"] = [1, 2, 3]
dic = {"first":{1:1},
"second":{2:"a"}}
print(dic)
func1(dic)
print(dic)
Dictionaries
• In summary, dictionaries:
• Can be iterated over
Output:
dic = {"first": 1, "second": 2, "third": 3}
for i in dic:
print(i)
How to get the values?
first
second
third
ONLY the keys will be returned.
Dictionaries
• In summary, dictionaries:
• Can be iterated over
Output:
dic = {"first": 1, "second": 2, "third": 3}
for i in dic:
print(dic[i])
1
2
3
Values can be accessed via indexing!
Adding Elements to a Dictionary
• How to add elements to a dictionary?
• By indexing the dictionary via a key and assigning a corresponding value
Output:
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic["fourth"] = 4
print(dic)
{'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}
Adding Elements to a Dictionary
• How to add elements to a dictionary?
• By indexing the dictionary via a key and assigning a corresponding value
Output:
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic[”second"] = 4
print(dic)
{'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second’: 4, 'third': 3}
If the key already exists,
the value will be overridden
Deleting Elements to a Dictionary
• How to delete elements in a dictionary?
• By using del
Output:
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic["fourth"] = 4
print(dic)
del dic["first"]
print(dic)
{'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}
{'second': 2, 'third': 3, 'fourth': 4}
Deleting Elements to a Dictionary
• How to delete elements in a dictionary?
• Or by using the function pop(key)
Output:
dic = {"first": 1, "second": 2, "third": 3}
print(dic)
dic["fourth"] = 4
print(dic)
dic.pop(“first”)
print(dic)
{'first': 1, 'second': 2, 'third': 3}
{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}
{'second': 2, 'third': 3, 'fourth': 4}
Dictionary Functions
• Many other functions can also be used with dictionaries
Function Description
dic.clear() Removes all the elements from dictionary dic
dic.copy() Returns a copy of dictionary dic
dic.items() Returns a list containing a tuple for each key-value pair in
dictionary dic
dic.get(k) Returns the value of the specified key k from dictionary dic
dic.keys() Returns a list containing all the keys of dictionary dic
dic.pop(k) Removes the element with the specified key k from dictionary dic
Dictionary Functions
• Many other functions can also be used with dictionaries
Function Description
dic.popitem() Removes the last inserted key-value pair in dictionary dic
dic.values() Returns a list of all the values in dictionary dic
Next Lecture…
• Practice on Tuples and Dictionaries

Weitere ähnliche Inhalte

Ähnlich wie Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx

GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfAsst.prof M.Gokilavani
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptxRamiHarrathi1
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Ziyauddin Shaik
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdfMariappanR3
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptxmohitesoham12
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdfAshaWankar1
 
Datatypes in Python.pdf
Datatypes in Python.pdfDatatypes in Python.pdf
Datatypes in Python.pdfking931283
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology InitiativeBasil Bibi
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Time and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptxTime and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptxdudelover
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Simplilearn
 
Python data type
Python data typePython data type
Python data typeJaya Kumari
 
02 Python Data Structure.pptx
02 Python Data Structure.pptx02 Python Data Structure.pptx
02 Python Data Structure.pptxssuser88c564
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptxYagna15
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfomprakashmeena48
 

Ähnlich wie Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx (20)

02python.ppt
02python.ppt02python.ppt
02python.ppt
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdf
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Datatypes in Python.pdf
Datatypes in Python.pdfDatatypes in Python.pdf
Datatypes in Python.pdf
 
Brixton Library Technology Initiative
Brixton Library Technology InitiativeBrixton Library Technology Initiative
Brixton Library Technology Initiative
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Time and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptxTime and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptx
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Python data type
Python data typePython data type
Python data type
 
02 Python Data Structure.pptx
02 Python Data Structure.pptx02 Python Data Structure.pptx
02 Python Data Structure.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 

Kürzlich hochgeladen

Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfDrew Moseley
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosVictor Morales
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 
Novel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsNovel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsResearcher Researcher
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTSneha Padhiar
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfModule-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfManish Kumar
 
List of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfList of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfisabel213075
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.elesangwon
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfNainaShrivastava14
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxStephen Sitton
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionSneha Padhiar
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodManicka Mamallan Andavar
 
OOP concepts -in-Python programming language
OOP concepts -in-Python programming languageOOP concepts -in-Python programming language
OOP concepts -in-Python programming languageSmritiSharma901052
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Sumanth A
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSsandhya757531
 

Kürzlich hochgeladen (20)

Immutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdfImmutable Image-Based Operating Systems - EW2024.pdf
Immutable Image-Based Operating Systems - EW2024.pdf
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitos
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 
Novel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsNovel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending Actuators
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdfModule-1-(Building Acoustics) Noise Control (Unit-3). pdf
Module-1-(Building Acoustics) Noise Control (Unit-3). pdf
 
List of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdfList of Accredited Concrete Batching Plant.pdf
List of Accredited Concrete Batching Plant.pdf
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
2022 AWS DNA Hackathon 장애 대응 솔루션 jarvis.
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
 
Turn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptxTurn leadership mistakes into a better future.pptx
Turn leadership mistakes into a better future.pptx
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
Cost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based questionCost estimation approach: FP to COCOMO scenario based question
Cost estimation approach: FP to COCOMO scenario based question
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument method
 
OOP concepts -in-Python programming language
OOP concepts -in-Python programming languageOOP concepts -in-Python programming language
OOP concepts -in-Python programming language
 
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
Robotics-Asimov's Laws, Mechanical Subsystems, Robot Kinematics, Robot Dynami...
 
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMSHigh Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
High Voltage Engineering- OVER VOLTAGES IN ELECTRICAL POWER SYSTEMS
 

Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx

  • 1. 15-110: Principles of Computing Sequences- Part IV (Tuples and Dictionaries) Lecture 15, October 23, 2018 Mohammad Hammoud Carnegie Mellon University in Qatar
  • 2. Today… • Last Session: • Sequences- Part III (Matrix Operations as an Application on Lists) • Today’s Session: • Sequences- Part IV: • Tuples • Dictionaries
  • 3. Tuples • Tuples are very similar to lists, but they are immutable (i.e., unchangeable) • Tuples are written with round brackets as follows: t1 = (1, 2, 3) t2 = (“a”, “b”, “c”, ”d”) t3 = (200, “A”, [4, 5], 3.2) print(t1) print(t2) print(t3)
  • 4. Tuples • Like lists, tuples can: • Contain any and different types of elements • Contain duplicate elements (e.g., (1, 1, 2)) • Be indexed exactly in the same way (i.e., using the [] brackets) • Be sliced exactly in the same way (i.e., using the [::] notation) • Be concatenated (e.g., t = (1, 2, 3) + (“a”, “b”, “c”)) • Be repeated (e.g., t = (“a”, “b”) * 10) • Be nested (e.g., t = ((1, 2), (3, 4), ((“a”, “b”, ”c”), 3.4)) • Be passed to a function, but will result in pass-by-value and not pass-by- reference outcome since it is immutable • Be iterated over
  • 5. Examples t1 = ("a", "b", "c") print(t1[::-1]) t2 = ("a", "b", "c") t3 = t1 + t2 print(t3) t3 = t3 * 4 print(t3) for i in t3: print(i, end = " ") print() This will print the elements of t1 in a reversed order, but will not change t1 itself since it is immutable This will concatenate t1 and t2 and assign the result to t3 (again, t1 and t2 will be unchanged since they are immutable) This will repeat t3 four times and assign the result to t3. Hence, t3 will be overwritten (i.e., NOT changed in place- because it is immutable-, but redefined with a new value)
  • 6. Examples t4 = ((1, 2, 3), ("a", "b", "c")) for j in t4: for k in j: print(k,end = " ") print() This is an example of nesting, where a matrix with 2 rows and 3 columns is created. The first row includes the elements 1, 2, and 3. The second row includes the elements “a”, “b”, and “c”. This outer loop iterates over each element in t4; that is, it gets first the element (1, 2, 3) and second the element (“a”, “b”, “c”) This inner loop iterates over each element read by the outer loop; that is, it first iterates over the elements of the element (1, 2, 3), and second it iterates over the elements of the element (“a”, “b”, “c”)
  • 7. Examples def func1(t): t = t * 2 t = (1, 2, 3) print(t) func1(t) print(t) This will output (1, 2, 3) This will also output (1, 2, 3) since tuples are immutable, hence, will always exhibit a passed-by-value behavior This change on t remains local to the function since a value of t was passed and not a reference to it
  • 8. Using Functions with Tuples • You can also use functions with tuples t1 = (1, 2, 3, 1, 5, 1) print(t1.count(1)) print(t1.index(1)) The count(x) function returns the number of elements with the specified value x (e.g., x is 1 in this example) The index(x) function returns the index of the first element with the specified value x (e.g., x is 1 in this example) Output: 3 0 In fact, Python has only these two built-in functions that can be used on tuples
  • 9. Towards Dictionaries • Lists and tuples hold elements with only integer indices • So in essence, each element has an index (or a key) which can only be an integer, and a value which can be of any type (e.g., in the above list/tuple, the first element has key 0 and value 45) • What if we want to store elements with non-integer indices (or keys)? 45 “Coding” 4.5 7 89 0 1 2 3 4 Integer Indices
  • 10. Dictionaries • In Python, you can use a dictionary to store elements with keys of any types (not necessarily only integers like lists and tuples) and values of any types as well • The above dictionary can be defined in Python as follows: dic = {"NUM":45, 1000:"coding", 2000:4.5, 3.4:7, "XXX":89} 45 “Coding” 4.5 7 89 “NUM” 1000 2000 3.4 “XXX” keys of different types Each element is a key:value pair, and elements are separated by commas key value Values of different types
  • 11. Dictionaries • In summary, dictionaries: • Can contain any and different types of elements (i.e., keys and values) • Can contain only unique keys but duplicate values • Can be indexed but only through keys (i.e., dic2[“a”] will return 1 but dic2[0] will return an error since there is no element with key 0 in dic2 above) Output: {'a': 2, 'b': 2} dic2 = {"a":1, "a":2, "b":2} print(dic2) The element “a”:2 will override the element “a”:1 because only ONE element can have key “a”
  • 12. Dictionaries • In summary, dictionaries: • CANNOT be concatenated • CANNOT be repeated • Can be nested (e.g., d = {"first":{1:1}, "second":{2:"a"}} • Can be passed to a function and will result in a pass-by-reference and not pass-by-value behavior since it is immutable (like lists) Output: {'first': {1: 1}, 'second': {2: 'a'}} {'first': [1, 2, 3], 'second': {2: 'a'}} def func1(d): d["first"] = [1, 2, 3] dic = {"first":{1:1}, "second":{2:"a"}} print(dic) func1(dic) print(dic)
  • 13. Dictionaries • In summary, dictionaries: • Can be iterated over Output: dic = {"first": 1, "second": 2, "third": 3} for i in dic: print(i) How to get the values? first second third ONLY the keys will be returned.
  • 14. Dictionaries • In summary, dictionaries: • Can be iterated over Output: dic = {"first": 1, "second": 2, "third": 3} for i in dic: print(dic[i]) 1 2 3 Values can be accessed via indexing!
  • 15. Adding Elements to a Dictionary • How to add elements to a dictionary? • By indexing the dictionary via a key and assigning a corresponding value Output: dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4}
  • 16. Adding Elements to a Dictionary • How to add elements to a dictionary? • By indexing the dictionary via a key and assigning a corresponding value Output: dic = {"first": 1, "second": 2, "third": 3} print(dic) dic[”second"] = 4 print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second’: 4, 'third': 3} If the key already exists, the value will be overridden
  • 17. Deleting Elements to a Dictionary • How to delete elements in a dictionary? • By using del Output: dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 print(dic) del dic["first"] print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} {'second': 2, 'third': 3, 'fourth': 4}
  • 18. Deleting Elements to a Dictionary • How to delete elements in a dictionary? • Or by using the function pop(key) Output: dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 print(dic) dic.pop(“first”) print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} {'second': 2, 'third': 3, 'fourth': 4}
  • 19. Dictionary Functions • Many other functions can also be used with dictionaries Function Description dic.clear() Removes all the elements from dictionary dic dic.copy() Returns a copy of dictionary dic dic.items() Returns a list containing a tuple for each key-value pair in dictionary dic dic.get(k) Returns the value of the specified key k from dictionary dic dic.keys() Returns a list containing all the keys of dictionary dic dic.pop(k) Removes the element with the specified key k from dictionary dic
  • 20. Dictionary Functions • Many other functions can also be used with dictionaries Function Description dic.popitem() Removes the last inserted key-value pair in dictionary dic dic.values() Returns a list of all the values in dictionary dic
  • 21. Next Lecture… • Practice on Tuples and Dictionaries