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

ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
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.
Guide to Programming with Python
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
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.
Lists Introduction to Computing Science and Programming I.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
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.
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.
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.
Lecture 04 – Models of memory Mutable and immutable data.
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.
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.
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.
10 - Python Dictionary John R. Woodward.
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
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.
COSC 1323 – Computer Science Concepts I
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
CS190/295 Programming in Python for Life Sciences: Lecture 6
6. Lists Let's Learn Python and Pygame
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
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
CS 1111 Introduction to Programming Fall 2018
Dictionaries Dictionary: object that stores a collection of data
(more) Python.
Dictionaries: Keeping track of pairs
Topics Sequences Lists Copying Lists Processing Lists
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
And now for something completely different . . .
Python Review
Lists [] First = [1, 2, 3, 4] Second = list[range(1,5)]
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Dictionary.
Tuple.
Introduction to Computer Science
Presentation transcript:

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

Sequences so far Strings "", tuples () General sequence functions/operators/methods len(seq) "w" in "word" seq[i] (indexing) seq[beg:end] (slicing) seq1 + seq2 (concatenation) "abc".index("a") for loops: iterates over a sequence for letter in "word": for idx in range(len("word")): while idx < len("word")

Objectives Lists are similar to tuples in many senses Create, index, and slice a list (similarly to tutle) Lists are mutable sequences (tuples are immutable) 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 NumPy (http://numpy.scipy.org/) Use dictionaries (not ordered!) to work with pairs of data Add and delete dictionary items Guide to Programming with Python

Lists are Similar to Tuples List: A mutable (changeable) sequence of any type Creating List inventory = [] inventory = ["sword", "armor", "shield", "healing potion"] Using len() function and in operator if "healing potion" in inventory: print "You will live to fight another day.” Indexing and slicing inventory[1], inventory[1:3] Concatenating lists list1 + list2 [ ] Tuple: inventory = (“sword”, “armor”, “shield”, “healing potion”) 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 Element Or Slice >>> inventory = ["sword", "armor", "shield", "healing potion", "gold", "gems"] >>> inventory[0] = "crossbow" >>> print inventory ['crossbow', 'armor', 'shield', 'healing potion', 'gold', 'gems’] >>> inventory[4:6] = ["orb of future telling"] ['crossbow', 'armor', 'shield', 'healing potion', 'orb of future telling'] (Replaces the two elements inventory[4] and inventory[5] with "orb of future telling”) Guide to Programming with Python

Deleting an Element or a Slice >>> inventory = ["crossbow", "armor", "shield", "healing potion", "orb of future telling"] >>> del inventory[2] >>> print inventory ['crossbow', 'armor', 'healing potion', 'orb of future telling'] >>> del inventory[:2] ['healing potion', 'orb of future telling’] Designate element to delete after del Guide to Programming with Python

List Methods Table 5.1: Selected list methods ascending order by default 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 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 scores = [("Moe", 1000), ("Larry", 1500), ("Curly", 3000)] scores[2] is the element of the list at position 2 scores[2][0] is the element at position 0 of scores[2] multiple indexing 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 scores[1][0] multiple indexing scores = [("Moe", 1000), ("Larry", 1500)] for entry in scores: score, name = entry print name, "\t", score Sequence unpacking: Automatically accessing each element of a sequence as a result of assignment statement Guide to Programming with Python

Variable References A variable refers to a place in memory where the value (or empty) is stored language = “Python” Variable assignment can be initial (creates a new box in the computer’s memory the first time a variable name is seen) shared (assign lists; default for mutable items) a = b = [] # both names will point to the same list copied (numbers, strings, tuples) “Python” language # All variables refer to same single list

Shared Reference – Changes Applied to All Variables Sharing References “red sweater” mike[2] = “red sweater” Then mr_dawson[2], and honey[2] => “red sweater” Shared reference could cause serious problem if you are not aware of this (see the Sodoku puzzle solver) Guide to Programming with Python

Avoid Shared References >>> 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 (but NOT for nested sequences) a = [1, 2, [3, 4]] b = a[:] b[1] = "22” b[2][0] = "33" Guide to Programming with Python

Using copy.deepcopy() Module: copy ref: http://docs.python.org/library/copy.html import copy b = copy.copy(a) #shallow copy, => b = a[:] b = copy.deepcopy(a) #deep copy of an object #A deep (shallow) copy constructs a new compound object and then, recursively, inserts copies (references) into it of the objects found in the original. Example: sokodu1 = copy.deepcopy(sokodu)

NumPy for Arrays of Numeric Numbers (instead of Using Nested Sequences) Initialize a 2D-array a = [[0]*3]*3 a[1][1] = 1 Ref: http://numpy.scipy.org/ import numpy numpy.zeros([3,3], int) # It has the “shared reference problem” 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 The Geek Translator Program Guide to Programming with Python

Creating Dictionaries geek = {"404" : "clueless.", "Uninstalled" : "being fired."} Creates new dictionary called geek geek has two entries or items 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 value 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 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 Don’t have to be unique Guide to Programming with Python

The Hangman Game V2 Guide to Programming with Python

Summary A list is a mutable sequence of any type You can add or remove list elements or slices A nested sequence is a sequence inside another sequence; access an element by using multiple indexing Sequence unpacking is the process of automatically accessing each element of a sequence A shared reference is a reference to an object, which has at least one other reference to it Guide to Programming with Python

Summary (continued) A dictionary is a mutable collection of key-value pairs In a dictionary, an item is a key-value pair In a dictionary, a key is an object used to look up another object In a dictionary, a value is an object that is returned when its corresponding key is looked up The in operator can be used to test if a dictionary contains a specific key Guide to Programming with Python

Summary (continued) A dictionary can’t contain multiple items with the same key A dictionary can contain multiple items with the same value Dictionary keys must be immutable Dictionary values can be mutable Guide to Programming with Python