Guide to Programming with Python

Slides:



Advertisements
Similar presentations
Dictionaries (aka hash tables or hash maps) Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas.
Advertisements

Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Dictionaries: Keeping track of pairs
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
Fundamentals of Python: From First Programs Through Data Structures
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Python Dictionary.
Sequences The range function returns a sequence
Lists Introduction to Computing Science and Programming I.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
Python Data Structures
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Lists in Python.
October 17, 2005ICP: Chapter 5: Lists and Dictionaries 1 Introduction to Computer Programming Chapter 5: Lists and Dictionaries Michael Scherger Department.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 14 Tuples, Sets, and Dictionaries 1.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Beyond Lists: Other Data Structures CS303E: Elements of Computers and Programming.
Chapter 7 Lists and Tuples. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Data Structures.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Daniel Jung. Types of Data Structures  Lists Stacks Queues  Tuples  Sets  Dictionaries.
Lists CS303E: Elements of Computers and Programming.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Introduction to Computing Using Python Dictionaries: Keeping track of pairs  Class dict  Class tuple.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
LECTURE 3 Python Basics Part 2. FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Programing: An Introduction to Computer Science
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
String and Lists Dr. José M. Reyes Álamo.
Intro to CS Nov 21, 2016.
Tuples and Lists.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
When to use Tuples instead of Lists
Containers and Lists CIS 40 – Introduction to Programming in Python
Chapter 4 Strings & Tuples
Lecture 10 Data Collections
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CISC101 Reminders Quiz 2 this week.
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Guide to Programming with Python
4. sequence data type Rocky K. C. Chang 16 September 2018
String and Lists Dr. José M. Reyes Álamo.
Chapter 5: Lists and Dictionaries
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
15-110: Principles of Computing
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Python Review
Lists [] First = [1, 2, 3, 4] Second = list[range(1,5)]
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Dictionary.
Introduction to Computer Science
Presentation transcript:

Guide to Programming with Python Chapter Five Lists and Dictionaries: The Hangman Game

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

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

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

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

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

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

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

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

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

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

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

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

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

Deleting a List Slice Designate slice to delete after del >>> 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

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

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

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

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 Ask class: How is remove() different from del? Guide to Programming with Python

The List sort() Method scores.sort() Sorts the elements of a list (ascending order by default) Guide to Programming with Python

The List reverse() Method scores.reverse() Reverses the order of elements in a list high_scores.py Guide to Programming with Python

Selected List Methods Table 5.1: Selected list methods Guide to Programming with Python

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

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

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

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

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

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

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

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

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

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

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

Shared References (continued) >>> mike = ["khakis", "dress shirt", "jacket"] >>> mr_dawson = mike >>> honey = mike >>> print mike ['khakis', 'dress shirt', 'jacket'] >>> print mr_dawson >>> print honey All variables refer to same single list Guide to Programming with Python

Shared References (continued) >>> honey[2] = "red sweater" >>> print honey ['khakis', 'dress shirt', 'red sweater'] >>> print mike >>> print mr_dawson Change to list through one variable reflects change for all variables because there is only one list Guide to Programming with Python

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

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

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

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

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

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

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

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

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

Selected Dictionary Methods Table 5.1: Selected dictionary methods Guide to Programming with Python

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

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

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

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

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? Guide to Programming with Python

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) Guide to Programming with Python