SlideShare a Scribd company logo
Guide to Programming with
Python
Chapter Five
Lists and Dictionaries: The Hangman Game
Guide to Programming with Python 2
Objectives
• Create, index, and slice a list
• Add and delete elements from a list
• Use list methods to append, sort, and reverse a list
• Use nested sequences to represent even more
complex information
• Use dictionaries to work with pairs of data
• Add and delete dictionary items
Guide to Programming with Python 3
The Hangman Game
Figure 5.1: Sample run of the Hangman game
Hmm… I wonder what the word could be.
Guide to Programming with Python 4
Using Lists
• Lists
– Sequences of any type
– Like tuples, but mutable (can be modified)
– Essentially can do everything tuples can, plus more
Guide to Programming with Python 5
Hero’s Inventory 3.0 Program
Figure 5.4: Sample run of the Hero’s Inventory 3.0 Program
The hero’s inventory is now represented by a list.
Guide to Programming with Python 6
Hero’s Inventory 3.0 Program
(continued)
Figure 5.5: Sample run of Hero’s Inventory 3.0 Program (continued)
Items can be added, modified, and deleted.
Guide to Programming with Python 7
Creating a List
• List: A mutable sequence of any type
• Creating an Empty List
inventory = []
• Creating a List with Elements
inventory = ["sword", "armor", "shield",
"healing potion"]
Guide to Programming with Python 8
Using len() and in with Lists
• The len() function with lists
– Just as with tuples, returns number of elements
print "You have", len(inventory), "items."
• The in operator with lists
– Just as with tuples, tests for element membership
if "healing potion" in inventory:
print "You will live to fight another day."
Guide to Programming with Python 9
Indexing and Slicing Lists
• Indexing Lists
– Just as with tuples, supply the position number of the
element in brackets
print "At index", index, "is", inventory[index]
• Slicing Lists
– Just as with tuples, supply the two end points,
separated by a colon, in brackets
print inventory[begin:end]
Guide to Programming with Python 10
Concatenating Lists
>>> inventory = ["sword", "armor", "shield",
"healing potion"]
>>> chest = ["gold", "gems"]
>>> inventory += chest
>>> print inventory
['sword', 'armor', 'shield', 'healing potion',
'gold', 'gems']
• Just as with tuples, concatenation operator, +,
works with lists
Guide to Programming with Python 11
Understanding List Mutability
• Mutable: Changeable
• Lists are mutable
– Elements (or slices) can be added
– Elements (or slices) can be removed
Guide to Programming with Python 12
Assigning a New List Element by
Index
>>> inventory = ["sword", "armor", "shield",
"healing potion", "gold", "gems"]
>>> inventory[0] = "crossbow"
>>> print inventory
['crossbow', 'armor', 'shield', 'healing potion',
'gold', 'gems']
• Unlike with tuples, you can assign a value to an
existing list element
Guide to Programming with Python 13
Assigning a New List Slice
>>> inventory = ["crossbow", "armor", "shield",
"healing potion", "gold", "gems"]
>>> inventory[4:6] = ["orb of future telling"]
>>> print inventory
['crossbow', 'armor', 'shield', 'healing potion',
'orb of future telling']
• Assignment statement replaces elements in slice
with new element
– Replaces the two elements inventory[4] and
inventory[5] with "orb of future telling"
Guide to Programming with Python 14
Deleting a List Element
>>> inventory = ["crossbow", "armor", "shield",
"healing potion",
"orb of future telling"]
>>> del inventory[2]
>>> print inventory
['crossbow', 'armor', 'healing potion', 'orb of
future telling']
• Designate element to delete after del
– Deletes element at position 2
Guide to Programming with Python 15
Deleting a List Slice
>>> inventory = ["crossbow", "armor",
"healing potion",
"orb of future telling"]
>>> del inventory[:2]
>>> print inventory
['healing potion', 'orb of future telling']
• Designate slice to delete after del
– Deletes slice made up of elements inventory[0]
and inventory[1]
hero’s_inventory3.py
Guide to Programming with Python 16
Using List Methods
• List methods manipulate lists
• Through list methods, you can:
– Add an element
– Remove an element
– Sort a list
– Reverse a list
– And more
Guide to Programming with Python 17
The High Scores Program
Figure 5.6: Sample run of the High Scores program
Behind the scenes, list methods do the bulk of the work.
Guide to Programming with Python 18
The List append() Method
scores.append(score)
• Adds element to the end of list
• Adds score to the end of list scores
Guide to Programming with Python 19
The List remove() Method
scores.remove(score)
• Removes first occurrence of a value from a list
• Attempting to remove a value that is not a member
of a list will generate an error
• Removes first occurrence of score from list scores
Guide to Programming with Python 20
The List sort() Method
scores.sort()
• Sorts the elements of a list (ascending order by
default)
Guide to Programming with Python 21
The List reverse() Method
scores.reverse()
• Reverses the order of elements in a list
high_scores.py
Guide to Programming with Python 22
Selected List Methods
Table 5.1: Selected list methods
Guide to Programming with Python 23
When to Use Tuples Instead of Lists
• Tuples are faster than lists
• Tuples’ immutability makes them perfect for
creating constants because they can’t change
• Sometimes tuples are required
• Rule of thumb: Use lists over tuples in most cases
Guide to Programming with Python 24
Using Nested Sequences
• Nested Sequence: A sequence inside another
sequence
• A list can contain lists or tuples
• A tuple can contain tuples or lists
Guide to Programming with Python 25
The High Scores 2.0 Program
Figure 5.7: Sample run of the High Scores 2.0 program
Improved version stores name with score through nested sequences.
Guide to Programming with Python 26
Creating Nested Sequences
>>> scores = [("Moe", 1000), ("Larry", 1500),
("Curly", 3000)]
>>> print scores
[('Moe', 1000), ('Larry', 1500), ('Curly', 3000)]
• scores is a nested sequence
• scores is a list of tuples
• scores has three elements, each of which is a tuple
Guide to Programming with Python 27
Accessing Nested Elements
>>> scores = [("Moe", 1000), ("Larry", 1500),
("Curly", 3000)]
>>> print scores[2]
('Curly', 3000)
>>> print scores[2][0]
Curly
• scores[2] is the element of the list at position 2
• scores[2][0] is the element at position 0 of
scores[2]
Guide to Programming with Python 28
Unpacking a Sequence
>>> name, score = ("Shemp", 175)
>>> print name
Shemp
>>> print score
175
• Sequence unpacking: Automatically accessing
each element of a sequence
• The tuple is unpacked as result of assignment
statement
Guide to Programming with Python 29
Accessing Elements of a Nested
Sequence
for entry in scores:
score, name = entry
print name, "t", score
• entry is an element of scores
• Assignment statement unpacks entry
• score is assigned first element of entry
• name is assigned second element of entry
Guide to Programming with Python 30
Appending Elements to a Nested
Sequence
entry = (score, name)
scores.append(entry)
• append() method works for any list, including a list
of sequences
• New tuple entry is created
• entry is appended to list scores as last element
high_scores2.py
Guide to Programming with Python 31
Shared References
Figure 5.8: A variable and the object it refers to
language refers to computer memory where "Python" is stored.
Guide to Programming with Python 32
Shared References (continued)
• Variables don’t store objects, they refer to objects
• Shared Reference: A reference to an object,
which has at least one other reference to it
• Shared references have significance for mutable
objects
Guide to Programming with Python 33
Shared References (continued)
Figure 5.9: A single object has three references to it.
Mike, mr_dawson and honey all refer to same single list.
Guide to Programming with Python 34
Shared References (continued)
>>> mike = ["khakis", "dress shirt", "jacket"]
>>> mr_dawson = mike
>>> honey = mike
>>> print mike
['khakis', 'dress shirt', 'jacket']
>>> print mr_dawson
['khakis', 'dress shirt', 'jacket']
>>> print honey
['khakis', 'dress shirt', 'jacket']
• All variables refer to same single list
Guide to Programming with Python 35
Shared References (continued)
>>> honey[2] = "red sweater"
>>> print honey
['khakis', 'dress shirt', 'red sweater']
>>> print mike
['khakis', 'dress shirt', 'red sweater']
>>> print mr_dawson
['khakis', 'dress shirt', 'red sweater']
• Change to list through one variable reflects change
for all variables because there is only one list
Guide to Programming with Python 36
Shared References (continued)
>>> mike = ["khakis", "dress shirt", "jacket"]
>>> honey = mike[:]
>>> honey[2] = "red sweater"
>>> print honey
['khakis', 'dress shirt', 'red sweater']
>>> print mike
['khakis', 'dress shirt', 'jacket']
• List slicing can create a new copy of a list and
avoid shared references
Guide to Programming with Python 37
Using Dictionaries
• Dictionary: A mutable collection of key-value
pairs
• Like tuple and list, dictionary is another built-in type
• Unlike tuples and lists, dictionaries don’t organize
data into sequences, but pairs
• Works like actual dictionary; look up one thing to
get another
• Look up a key to get a value
Guide to Programming with Python 38
The Geek Translator Program
Figure 5.10: Sample run of the Geek Translator program
Geek terms and definitions are accessed with a dictionary.
Guide to Programming with Python 39
Creating Dictionaries
geek = {"404" : "clueless.",
"Uninstalled" : "being fired."}
• Creates new dictionary called geek
• geek has two entries or items (or elements)
• Each item is made up of a key and a value
• 404 is a key of one item; use it to look up value
"clueless."
• Create dictionary by pairing values with colon,
separated by commas, surrounded by curly braces
Guide to Programming with Python 40
Using a Key to Retrieve a Value
>>> geek["404"]
'clueless.'
>>> geek["Uninstalled"]
'being fired.'
• Use key as index to get value
• Cannot use value as index to get key
• Using non-existent key as index produces error
• Dictionaries don't have position numbers – no
order
Guide to Programming with Python 41
Testing for a Key with the in Operator
>>> if "Dancing Baloney" in geek:
print "I know what Dancing Baloney is."
else:
print "I have no idea what Dancing Baloney is."
I have no idea what Dancing Baloney is.
• Use the in operator to test for key
• Condition is True if key exists in dictionary, False
otherwise
• in operator can't be used to test for dictionary
values
Guide to Programming with Python 42
The Dictionary get() Method
>>> geek.get("404")
'clueless.'
>>> geek.get("Dancing Baloney")
None
>>> geek.get("Dancing Baloney", "I have no idea.")
'I have no idea.'
• Used for retrieving value based on key
• Has built-in safety net for handling non-existent key
– If key exists, returns associated value
– If key doesn’t exist, returns a default, program-
provided value (or None if no default is provided)
Guide to Programming with Python 43
Adding a Key-Value Pair
geek["Link Rot"] = "process by which web page links
become obsolete."
• Dictionaries are mutable
• Add item by assigning value to dictionary indexed
by key
• Overwrites current entry if key already exists in
dictionary
Guide to Programming with Python 44
Deleting a Key-Value Pair
del geek["404"]
• Removes key-value pair if key exists
• Generates error if key doesn’t exist
geek_translator.py
Guide to Programming with Python 45
Selected Dictionary Methods
Table 5.1: Selected dictionary methods
Guide to Programming with Python 46
Dictionary Requirements
• Keys
– Must be unique
– Must be immutable
• Values
– Can be mutable or immutable
– Doesn’t have to be unique
hangman.py
Guide to Programming with Python 47
Summary
• A list is an immutable sequence of any type, True
or False?
– False (lists are mutable)
• You can append, remove, or change list elements
and slices, True or False?
– True
• A sequence inside another sequence is called
what?
– a nested sequence
Guide to Programming with Python 48
Summary (continued)
• What do you call it when you allow Python to
automatically accessing multiple elements of a
sequence and assign them to multiple variables?
– sequence unpacking
• What is a shared reference?
– a reference to an object, which has at least one other
reference to it
• If my_list and your_list are shared references and
the code changes the third element of my_list to
“Forbidden Zone”, what is the third element of
your_list?
– “Forbidden Zone”
Guide to Programming with Python 49
Summary (continued)
• A dictionary is a mutable collection of what?
– key-value pairs
• In a dictionary, each item is what?
– a key-value pair
• In a dictionary, a key is an object that allows you to
do what?
– look up a value object
• In a dictionary, a value is an object that is returned
when you do what?
– look up its corresponding key
Guide to Programming with Python 50
Summary (continued)
• The in operator can be used to test if a dictionary
contains a specific key, True or False?
– True
• The in operator can be used to test if a dictionary
contains a specific value, True or False?
– False
• A dictionary can contain multiple items with the
same key, True or False?
– False
Guide to Programming with Python 51
Summary (continued)
• A dictionary can contain multiple items with the
same value, True or False?
– True
• Dictionary keys must be immutable, True or False?
– True (keys must be immutable)
• Dictionary values must be immutable, True or
False?
– False (values may be mutable)
Ad

More Related Content

Similar to Python Lists and Dictonary. Data Structures (20)

Python lists
Python listsPython lists
Python lists
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Python programming
Python programmingPython programming
Python programming
sirikeshava
 
Pa2 session 1
Pa2 session 1Pa2 session 1
Pa2 session 1
aiclub_slides
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
Koteswari Kasireddy
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
Python_IoT.pptx
Python_IoT.pptxPython_IoT.pptx
Python_IoT.pptx
SwatiChoudhary95
 
Module 3,4.pptx
Module 3,4.pptxModule 3,4.pptx
Module 3,4.pptx
SandeepR95
 
python_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptxpython_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Python introduction data structures lists etc
Python introduction data structures lists etcPython introduction data structures lists etc
Python introduction data structures lists etc
ssuser26ff68
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
rehanafarheenece
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
ssuser492e7f
 
Data types usually used in python for coding
Data types usually used in python for codingData types usually used in python for coding
Data types usually used in python for coding
PriyankaRajaboina
 
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptxUNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
 
Presentation python programming vtu 6th sem
Presentation python programming vtu 6th semPresentation python programming vtu 6th sem
Presentation python programming vtu 6th sem
ssuser8f6b1d1
 
UNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering studentsUNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering students
SabarigiriVason
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
Ahmet Bulut
 
tupple.pptx
tupple.pptxtupple.pptx
tupple.pptx
satyabratPanda2
 
An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1An Introduction To Python - Lists, Part 1
An Introduction To Python - Lists, Part 1
Blue Elephant Consulting
 
Python lab basics
Python lab basicsPython lab basics
Python lab basics
Abi_Kasi
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Python programming
Python programmingPython programming
Python programming
sirikeshava
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
Module 3,4.pptx
Module 3,4.pptxModule 3,4.pptx
Module 3,4.pptx
SandeepR95
 
python_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptxpython_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Python introduction data structures lists etc
Python introduction data structures lists etcPython introduction data structures lists etc
Python introduction data structures lists etc
ssuser26ff68
 
Data types usually used in python for coding
Data types usually used in python for codingData types usually used in python for coding
Data types usually used in python for coding
PriyankaRajaboina
 
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptxUNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
 
Presentation python programming vtu 6th sem
Presentation python programming vtu 6th semPresentation python programming vtu 6th sem
Presentation python programming vtu 6th sem
ssuser8f6b1d1
 
UNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering studentsUNIT-4.pptx python for engineering students
UNIT-4.pptx python for engineering students
SabarigiriVason
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
Ahmet Bulut
 
Python lab basics
Python lab basicsPython lab basics
Python lab basics
Abi_Kasi
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 

Recently uploaded (20)

Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Cultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptxCultivation Practice of Onion in Nepal.pptx
Cultivation Practice of Onion in Nepal.pptx
UmeshTimilsina1
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Ad

Python Lists and Dictonary. Data Structures

  • 1. Guide to Programming with Python Chapter Five Lists and Dictionaries: The Hangman Game
  • 2. Guide to Programming with Python 2 Objectives • Create, index, and slice a list • Add and delete elements from a list • Use list methods to append, sort, and reverse a list • Use nested sequences to represent even more complex information • Use dictionaries to work with pairs of data • Add and delete dictionary items
  • 3. Guide to Programming with Python 3 The Hangman Game Figure 5.1: Sample run of the Hangman game Hmm… I wonder what the word could be.
  • 4. Guide to Programming with Python 4 Using Lists • Lists – Sequences of any type – Like tuples, but mutable (can be modified) – Essentially can do everything tuples can, plus more
  • 5. Guide to Programming with Python 5 Hero’s Inventory 3.0 Program Figure 5.4: Sample run of the Hero’s Inventory 3.0 Program The hero’s inventory is now represented by a list.
  • 6. Guide to Programming with Python 6 Hero’s Inventory 3.0 Program (continued) Figure 5.5: Sample run of Hero’s Inventory 3.0 Program (continued) Items can be added, modified, and deleted.
  • 7. Guide to Programming with Python 7 Creating a List • List: A mutable sequence of any type • Creating an Empty List inventory = [] • Creating a List with Elements inventory = ["sword", "armor", "shield", "healing potion"]
  • 8. Guide to Programming with Python 8 Using len() and in with Lists • The len() function with lists – Just as with tuples, returns number of elements print "You have", len(inventory), "items." • The in operator with lists – Just as with tuples, tests for element membership if "healing potion" in inventory: print "You will live to fight another day."
  • 9. Guide to Programming with Python 9 Indexing and Slicing Lists • Indexing Lists – Just as with tuples, supply the position number of the element in brackets print "At index", index, "is", inventory[index] • Slicing Lists – Just as with tuples, supply the two end points, separated by a colon, in brackets print inventory[begin:end]
  • 10. Guide to Programming with Python 10 Concatenating Lists >>> inventory = ["sword", "armor", "shield", "healing potion"] >>> chest = ["gold", "gems"] >>> inventory += chest >>> print inventory ['sword', 'armor', 'shield', 'healing potion', 'gold', 'gems'] • Just as with tuples, concatenation operator, +, works with lists
  • 11. Guide to Programming with Python 11 Understanding List Mutability • Mutable: Changeable • Lists are mutable – Elements (or slices) can be added – Elements (or slices) can be removed
  • 12. Guide to Programming with Python 12 Assigning a New List Element by Index >>> inventory = ["sword", "armor", "shield", "healing potion", "gold", "gems"] >>> inventory[0] = "crossbow" >>> print inventory ['crossbow', 'armor', 'shield', 'healing potion', 'gold', 'gems'] • Unlike with tuples, you can assign a value to an existing list element
  • 13. Guide to Programming with Python 13 Assigning a New List Slice >>> inventory = ["crossbow", "armor", "shield", "healing potion", "gold", "gems"] >>> inventory[4:6] = ["orb of future telling"] >>> print inventory ['crossbow', 'armor', 'shield', 'healing potion', 'orb of future telling'] • Assignment statement replaces elements in slice with new element – Replaces the two elements inventory[4] and inventory[5] with "orb of future telling"
  • 14. Guide to Programming with Python 14 Deleting a List Element >>> inventory = ["crossbow", "armor", "shield", "healing potion", "orb of future telling"] >>> del inventory[2] >>> print inventory ['crossbow', 'armor', 'healing potion', 'orb of future telling'] • Designate element to delete after del – Deletes element at position 2
  • 15. Guide to Programming with Python 15 Deleting a List Slice >>> inventory = ["crossbow", "armor", "healing potion", "orb of future telling"] >>> del inventory[:2] >>> print inventory ['healing potion', 'orb of future telling'] • Designate slice to delete after del – Deletes slice made up of elements inventory[0] and inventory[1] hero’s_inventory3.py
  • 16. Guide to Programming with Python 16 Using List Methods • List methods manipulate lists • Through list methods, you can: – Add an element – Remove an element – Sort a list – Reverse a list – And more
  • 17. Guide to Programming with Python 17 The High Scores Program Figure 5.6: Sample run of the High Scores program Behind the scenes, list methods do the bulk of the work.
  • 18. Guide to Programming with Python 18 The List append() Method scores.append(score) • Adds element to the end of list • Adds score to the end of list scores
  • 19. Guide to Programming with Python 19 The List remove() Method scores.remove(score) • Removes first occurrence of a value from a list • Attempting to remove a value that is not a member of a list will generate an error • Removes first occurrence of score from list scores
  • 20. Guide to Programming with Python 20 The List sort() Method scores.sort() • Sorts the elements of a list (ascending order by default)
  • 21. Guide to Programming with Python 21 The List reverse() Method scores.reverse() • Reverses the order of elements in a list high_scores.py
  • 22. Guide to Programming with Python 22 Selected List Methods Table 5.1: Selected list methods
  • 23. Guide to Programming with Python 23 When to Use Tuples Instead of Lists • Tuples are faster than lists • Tuples’ immutability makes them perfect for creating constants because they can’t change • Sometimes tuples are required • Rule of thumb: Use lists over tuples in most cases
  • 24. Guide to Programming with Python 24 Using Nested Sequences • Nested Sequence: A sequence inside another sequence • A list can contain lists or tuples • A tuple can contain tuples or lists
  • 25. Guide to Programming with Python 25 The High Scores 2.0 Program Figure 5.7: Sample run of the High Scores 2.0 program Improved version stores name with score through nested sequences.
  • 26. Guide to Programming with Python 26 Creating Nested Sequences >>> scores = [("Moe", 1000), ("Larry", 1500), ("Curly", 3000)] >>> print scores [('Moe', 1000), ('Larry', 1500), ('Curly', 3000)] • scores is a nested sequence • scores is a list of tuples • scores has three elements, each of which is a tuple
  • 27. Guide to Programming with Python 27 Accessing Nested Elements >>> scores = [("Moe", 1000), ("Larry", 1500), ("Curly", 3000)] >>> print scores[2] ('Curly', 3000) >>> print scores[2][0] Curly • scores[2] is the element of the list at position 2 • scores[2][0] is the element at position 0 of scores[2]
  • 28. Guide to Programming with Python 28 Unpacking a Sequence >>> name, score = ("Shemp", 175) >>> print name Shemp >>> print score 175 • Sequence unpacking: Automatically accessing each element of a sequence • The tuple is unpacked as result of assignment statement
  • 29. Guide to Programming with Python 29 Accessing Elements of a Nested Sequence for entry in scores: score, name = entry print name, "t", score • entry is an element of scores • Assignment statement unpacks entry • score is assigned first element of entry • name is assigned second element of entry
  • 30. Guide to Programming with Python 30 Appending Elements to a Nested Sequence entry = (score, name) scores.append(entry) • append() method works for any list, including a list of sequences • New tuple entry is created • entry is appended to list scores as last element high_scores2.py
  • 31. Guide to Programming with Python 31 Shared References Figure 5.8: A variable and the object it refers to language refers to computer memory where "Python" is stored.
  • 32. Guide to Programming with Python 32 Shared References (continued) • Variables don’t store objects, they refer to objects • Shared Reference: A reference to an object, which has at least one other reference to it • Shared references have significance for mutable objects
  • 33. Guide to Programming with Python 33 Shared References (continued) Figure 5.9: A single object has three references to it. Mike, mr_dawson and honey all refer to same single list.
  • 34. Guide to Programming with Python 34 Shared References (continued) >>> mike = ["khakis", "dress shirt", "jacket"] >>> mr_dawson = mike >>> honey = mike >>> print mike ['khakis', 'dress shirt', 'jacket'] >>> print mr_dawson ['khakis', 'dress shirt', 'jacket'] >>> print honey ['khakis', 'dress shirt', 'jacket'] • All variables refer to same single list
  • 35. Guide to Programming with Python 35 Shared References (continued) >>> honey[2] = "red sweater" >>> print honey ['khakis', 'dress shirt', 'red sweater'] >>> print mike ['khakis', 'dress shirt', 'red sweater'] >>> print mr_dawson ['khakis', 'dress shirt', 'red sweater'] • Change to list through one variable reflects change for all variables because there is only one list
  • 36. Guide to Programming with Python 36 Shared References (continued) >>> mike = ["khakis", "dress shirt", "jacket"] >>> honey = mike[:] >>> honey[2] = "red sweater" >>> print honey ['khakis', 'dress shirt', 'red sweater'] >>> print mike ['khakis', 'dress shirt', 'jacket'] • List slicing can create a new copy of a list and avoid shared references
  • 37. Guide to Programming with Python 37 Using Dictionaries • Dictionary: A mutable collection of key-value pairs • Like tuple and list, dictionary is another built-in type • Unlike tuples and lists, dictionaries don’t organize data into sequences, but pairs • Works like actual dictionary; look up one thing to get another • Look up a key to get a value
  • 38. Guide to Programming with Python 38 The Geek Translator Program Figure 5.10: Sample run of the Geek Translator program Geek terms and definitions are accessed with a dictionary.
  • 39. Guide to Programming with Python 39 Creating Dictionaries geek = {"404" : "clueless.", "Uninstalled" : "being fired."} • Creates new dictionary called geek • geek has two entries or items (or elements) • Each item is made up of a key and a value • 404 is a key of one item; use it to look up value "clueless." • Create dictionary by pairing values with colon, separated by commas, surrounded by curly braces
  • 40. Guide to Programming with Python 40 Using a Key to Retrieve a Value >>> geek["404"] 'clueless.' >>> geek["Uninstalled"] 'being fired.' • Use key as index to get value • Cannot use value as index to get key • Using non-existent key as index produces error • Dictionaries don't have position numbers – no order
  • 41. Guide to Programming with Python 41 Testing for a Key with the in Operator >>> if "Dancing Baloney" in geek: print "I know what Dancing Baloney is." else: print "I have no idea what Dancing Baloney is." I have no idea what Dancing Baloney is. • Use the in operator to test for key • Condition is True if key exists in dictionary, False otherwise • in operator can't be used to test for dictionary values
  • 42. Guide to Programming with Python 42 The Dictionary get() Method >>> geek.get("404") 'clueless.' >>> geek.get("Dancing Baloney") None >>> geek.get("Dancing Baloney", "I have no idea.") 'I have no idea.' • Used for retrieving value based on key • Has built-in safety net for handling non-existent key – If key exists, returns associated value – If key doesn’t exist, returns a default, program- provided value (or None if no default is provided)
  • 43. Guide to Programming with Python 43 Adding a Key-Value Pair geek["Link Rot"] = "process by which web page links become obsolete." • Dictionaries are mutable • Add item by assigning value to dictionary indexed by key • Overwrites current entry if key already exists in dictionary
  • 44. Guide to Programming with Python 44 Deleting a Key-Value Pair del geek["404"] • Removes key-value pair if key exists • Generates error if key doesn’t exist geek_translator.py
  • 45. Guide to Programming with Python 45 Selected Dictionary Methods Table 5.1: Selected dictionary methods
  • 46. Guide to Programming with Python 46 Dictionary Requirements • Keys – Must be unique – Must be immutable • Values – Can be mutable or immutable – Doesn’t have to be unique hangman.py
  • 47. Guide to Programming with Python 47 Summary • A list is an immutable sequence of any type, True or False? – False (lists are mutable) • You can append, remove, or change list elements and slices, True or False? – True • A sequence inside another sequence is called what? – a nested sequence
  • 48. Guide to Programming with Python 48 Summary (continued) • What do you call it when you allow Python to automatically accessing multiple elements of a sequence and assign them to multiple variables? – sequence unpacking • What is a shared reference? – a reference to an object, which has at least one other reference to it • If my_list and your_list are shared references and the code changes the third element of my_list to “Forbidden Zone”, what is the third element of your_list? – “Forbidden Zone”
  • 49. Guide to Programming with Python 49 Summary (continued) • A dictionary is a mutable collection of what? – key-value pairs • In a dictionary, each item is what? – a key-value pair • In a dictionary, a key is an object that allows you to do what? – look up a value object • In a dictionary, a value is an object that is returned when you do what? – look up its corresponding key
  • 50. Guide to Programming with Python 50 Summary (continued) • The in operator can be used to test if a dictionary contains a specific key, True or False? – True • The in operator can be used to test if a dictionary contains a specific value, True or False? – False • A dictionary can contain multiple items with the same key, True or False? – False
  • 51. Guide to Programming with Python 51 Summary (continued) • A dictionary can contain multiple items with the same value, True or False? – True • Dictionary keys must be immutable, True or False? – True (keys must be immutable) • Dictionary values must be immutable, True or False? – False (values may be mutable)

Editor's Notes

  • #19: Ask class: How is remove() different from del?
  翻译: