Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.

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 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.
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.
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.
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.
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.
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.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 2.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
Lecture 04 – Models of memory Mutable and immutable data.
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.
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.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
Python Programing: An Introduction to Computer Science
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
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.
Python Lists and Sequences Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark List properties What are lists? A list is a mutable.
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.
Tuples and Lists.
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
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
6. Lists Let's Learn Python and Pygame
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
Dictionaries: Keeping track of pairs
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CHAPTER 4: Lists, Tuples and Dictionaries
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
And now for something completely different . . .
Python Review
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 (data structure); 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 tuple)  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 (  Use dictionaries (not ordered!) to work with pairs of data –Add and delete dictionary items  Understanding sorting algorithms Guide to Programming with Python 3

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 Guide to Programming with Python4 Tuple: inventory = (“sword”, “armor”, “shield”, “healing potion”) [ ]

Understanding List Mutability  Mutable: Changeable  Lists are mutable –Elements (or slices) can be added –Elements (or slices) can be removed Guide to Programming with Python5

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"] >>> print inventory ['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 Python6

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] >>> print inventory ['healing potion', 'orb of future telling’] Guide to Programming with Python7 Designate element to delete after del

List Methods Table 5.1: Selected list methods Guide to Programming with Python8 ascending order by default

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 Python9

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] Guide to Programming with Python10 multiple indexing

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 Python11

Accessing Elements of a Nested Sequence scores = [("Moe", 1000), ("Larry", 1500)] for entry in scores: score, name = entry print name, "\t", score Guide to Programming with Python12 Sequence unpacking: Automatically accessing each element of a sequence as a result of assignment statement scores[1][0] multiple indexing

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

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 15

Using copy.deepcopy()  Module: copy –ref: 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: Ref: import numpy numpy.zeros([3,3], int) Guide to Programming with Python17 # It has the “shared reference problem”

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 Python18

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 Python19

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 Python20

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 Python21

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 Python22

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 Python23

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 Python24

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

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 Python26

The Hangman Game V2 Guide to Programming with Python27

Sorting Algorithms  What’s sorting: an operation that segregates items into groups according to specified criterion.  Sorting algorithms: bubble sort, selection sort, insertion sort, merge sort, heap sort, quick sort, radix sort, swap sort, etc

Bubble Sort  Smaller elements "bubble" to the top of the list.  Only uses comparisons to operate on elements (a comparison sort.)  Simple implementation but not efficient for sorting large lists  How it works: –Start from the beginning of a list, compare every adjacent pair, swap their position if they are not in the right order. After each iteration, one less element (the last one) is needed to be compared until there is no more element left to be compared or no more swaps are made in one iteration. Guide to Programming with Python29

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 Python30

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 Python31

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 Python32

Lists vs. Arrays  Python lists are very flexible and can hold completely heterogeneous, arbitrary data  Array can only be used for specific types, whereas lists can be used for any object.  Arrays may be more efficient for some numerical computation.  If you're going to be using arrays, consider the numpy or scipy packages. Guide to Programming with Python33

Data Types and Data Structures  Data types vs. data structures –A data type is a well-defined collection of data with a well-defined set of operations on it. (int, float, etc) –A data structure is an actual implementation of a particular abstract data type. (tree, graph, etc)  Building data structures from lists, dictionaries, etc Guide to Programming with Python34