Sharing, mutability, and immutability

Slides:



Advertisements
Similar presentations
Python Data Structures CMSC 201. Built in Types Today we will be talking about some other built in types in python! Tuples Sets Dictionaries.
Advertisements

Dictionaries: Keeping track of pairs
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
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.
Data Structures UW CSE 190p Summer >>> xs = range(3) >>> xs = [1,2,3] >>> xs = [‘a’,’b’,’c’] >>> xs = [1, ‘a’, 3] >>> xs = [[1,2,3], [‘a’,’b’,’c’]]
Introduction to Python and programming Michael Ernst UW CSE 190p Summer 2012.
Recitation 1 Programming for Engineers in Python.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
UW CSE 190p Section 8/2, Summer 2012 Dun-Yu Hsiao.
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.
Introduction to Python and programming Ruth Anderson UW CSE 140 Winter
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Lecture 04 – Models of memory Mutable and immutable data.
Tuples Chapter 10 Python for Informatics: Exploring Information
Python Data Structures CMSC 201. Built in Types Today we will be talking about some other built in types in python! Tuples Sets Dictionaries.
Collections Michael Ernst CSE 190p University of Washington.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Dictionaries Ruth Anderson CSE 160 University of Washington 1.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Dictionaries Ruth Anderson UW CSE 160 Winter
Equality, references and mutability COMPSCI 105 SS 2015 Principles of Computer Science.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
10 - Python Dictionary John R. Woodward.
Sharing, mutability, and immutability
Python – May 18 Quiz Relatives of the list: Tuple Dictionary Set
Algorithmic complexity: Speed of algorithms
CSC 458– Predictive Analytics I, Fall 2017, Intro. To Python
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
CS-104 Final Exam Review Victor Norman.
Introduction to Python and programming
The Python Data Model UW CSE 190p Summer 2012.
Ruth Anderson CSE 140 University of Washington
Sharing, mutability, and immutability
Ruth Anderson UW CSE 160 Spring 2018
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lists Part 1 Taken from notes by Dr. Neil Moore
Introduction to Python and programming
More Loop Examples Functions and Parameters
Ruth Anderson UW CSE 160 Winter 2017
Introduction to Python and programming
Ruth Anderson University of Washington CSE 160 Spring 2018
Sharing, mutability, and immutability
Sharing, mutability, and immutability
CSC 458– Predictive Analytics I, Fall 2018, Intro. To Python
Python for Informatics: Exploring Information
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Ruth Anderson UW CSE 160 Winter 2017
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Algorithmic complexity: Speed of algorithms
Introduction to Python and programming
Lists Part 1 Taken from notes by Dr. Neil Moore
Python Primer 1: Types and Operators
Sharing, mutability, and immutability
Michael Ernst CSE 140 University of Washington
Michael Ernst CSE 140 University of Washington
Nate Brunelle Today: Dictionaries
Reference semantics, variables and names
(more) Python.
Dictionaries: Keeping track of pairs
Ruth Anderson CSE 160 University of Washington
Python Review
Ruth Anderson UW CSE 160 Spring 2018
CSE 231 Lab 6.
Introduction to Python and programming
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

Sharing, mutability, and immutability Ruth Anderson UW CSE 160 Winter 2017

Copying and mutation See in python tutor list1 = ["e1", "e2", "e3", "e4"] list2 = list1 list3 = list(list1) # make a copy; also “list1[:]” print list1, list2, list3 list1.append("e5") list2.append("e6") list3.append("e7") list1 = list3 list1.append("e8") After slide 3, come back to this slide. Q: which of these lines are reassigning a variable vs. mutating an object?

Variable reassignment vs. Object mutation Reassigning a variable changes a binding, it does not change (mutate) any object Reassigning is always done via the syntax: myvar = expr size = 6 list2 = list1 Mutating (changing) an object does not change any variable binding Two syntaxes: Examples: left_expr = right_expr mylist[3] = myvalue expr.method(args…) mylist.append(myvalue) Changes what the variables size and list2 are bound to Changes something about the object that mylist refers to

Example: Variable reassignment or Object mutation? def no_change(lst): """does NOT modify what lst refers to, instead re-binds lst""" lst = lst + [99] def change_val(lst): """modifies object lst refers to""" lst[0] = 13 def append_val(lst): lst.append(99) lst2 = [1, 2] no_change(lst2) change_val(lst2) append_val(lst2) See in python tutor

New and old values Every expression evaluates to a value It might be a new value It might be a value that already exists A constructor evaluates to a new value: [3, 1, 4, 1, 5, 9] [3, 1, 4] + [1, 5, 9] mylist = [[3, 1], [4, 1]] An access expression evaluates to an existing value: mylist[1] What does a function call evaluate to? Here the right hand side of = is a constructor A: Depends!

An aside: List notation Possibly misleading notation: More accurate, but more verbose, notation: “four” “score” “and” “seven” “years” “four” “score” “and” “seven” “years” “four” “score” “and” “seven” “years”

Aside: Object identity See in python tutor An object’s identity never changes Can think of it as its address in memory Its value of the object (the thing it represents) may change mylist = [1, 2, 3] otherlist = mylist mylist.append(4) mylist is otherlist ⇒ True mylist and otherlist refer to the exact same object mylist == [1, 2, 3, 4] ⇒ True The object mylist refers to is equal to the object [1,2,3,4] (but they are two different objects) mylist is [1, 2, 3, 4] ⇒ False The object mylist refers to is not the exact same object as the object [1,2,3,4] mylist = [1, 2, 3] otherlist = mylist mylist.append(4) print mylist is otherlist # True print mylist == [1, 2, 3, 4] # True print mylist is [1, 2, 3, 4] # False newlist = mylist[:] print newlist is mylist # False  this is the only one that differs for a copy print newlist == [1, 2, 3, 4] # True print newlist is [1, 2, 3, 4] # False --------------------------- print id(mylist) print id(otherlist) print mylist is otherlist print mylist == [1, 2, 3, 4] print mylist is [1, 2, 3, 4] print id([1, 2, 3, 4]) print [1, 2, 3, 4] is [1, 2, 3, 4] print [1, 2, 3, 4] == [1, 2, 3, 4] Moral: Use == to check for equality, NOT is

Object type and variable type An object’s type never changes A variable can get rebound to a value of a different type Example: The variable a can be bound to an int or a list a = 5 5 is always an int a = [1, 2, 3, 4] [1, 2, 3, 4] is always a list A type indicates: what operations are allowed the set of representable values type(object) returns the type of an object

New datatype: tuple A tuple represents an ordered sequence of values Example: tuple “four” “score” “and” “seven” “years” tuple “four” “score” “and” “seven” “years” “four” “score” “and” “seven” “years”

Tuple operations Constructors Queries Mutators Literals: Use parentheses ("four", "score", "and", "seven", "years") (3, 1) + (4, 1) => (3, 1, 4, 1) Queries Just like lists Mutators None!

Immutable datatype An immutable datatype is one that doesn’t have any functions in the third category: Constructors Queries Mutators: None! Immutable datatypes: int, float, boolean, string, function, tuple, frozenset Mutable datatypes: list, dictionary, set

Remember: Not every value may be placed in a set Set elements must be immutable values int, float, bool, string, tuple not: list, set, dictionary The set itself is mutable (e.g. we can add and remove elements) Goal: only set operations change the set after “myset.add(x)”, x in myset  True y in myset always evaluates to the same value Both conditions should hold until myset is changed Mutable elements can violate these goals Aside: frozenset must contain immutable values and is itself immutable (cannot add and remove elements)

Remember: Not every value is allowed to be a key in a dictionary Keys must be immutable values int, float, bool, string, tuple of immutable types not: list, set, dictionary The dictionary itself is mutable (e.g. we can add and remove elements) Goal: only dictionary operations change the keyset after “mydict[x] = y”, mydict[x]  y if a == b, then mydict[a] == mydict[b] These conditions should hold until mydict is changed Mutable keys can violate these goals

Python’s Data Model All data is represented by objects Each object has: an identity Never changes Think of this as address in memory Test with is (but you rarely need to do so) a type a value Can change for mutable objects Cannot change for immutable objects Test with == Why even discuss these functions? Students shouldn’t use them id(obj) returns the object’s identity type(obj) returns the object’s type

Mutable and Immutable Types Immutable datatypes: int, float, boolean, string, function, tuple, frozenset Mutable datatypes: list, dictionary, set Note: a set is mutable, but a frozenset is immutable

Tuples are immutable Lists are mutable See in python tutor def updaterecord(record, position, value): """Change the value at the given position""" record[position] = value mylist = [1,2,3] mytuple = (1,2,3) updaterecord(mylist, 1, 10) print mylist updaterecord(mytuple, 1, 10) print mytuple

Increment Example def increment(uniquewords, word): See in python tutor def increment(uniquewords, word): """increment the count for word""" if uniquewords.has_key(word): uniquewords[word] = uniquewords[word] + 1 else: uniquewords[word] = 1 mywords = dict() increment(mywords, "school") print mywords def increment(value): """increment the value???""" value = value + 1 myval = 5 increment(myval) print myval def increment(uniquewords, word): """increment the count for word""" if uniquewords.has_key(word): uniquewords[word] = uniquewords[word] + 1 else: uniquewords[word] = 1 mywords = dict() increment(mywords, "school") print mywords def increment(value): """increment the value???""" value = value + 1 myval = 5 increment(myval) print myval

Increment Example (cont.) >>> def increment(uniquewords, word): ... """increment the count for word""" ... if uniquewords.has_key(word): uniquewords[word] = uniquewords[word] + 1 else: uniquewords[word] = 1 >>> mywords = dict() >>> increment(mywords, "school") >>> print mywords {'school': 1} >>> def increment(value): ... """increment the value???""" ... value = value + 1 >>> myval = 5 >>> increment(myval) >>> print myval 5 def increment(uniquewords, word): """increment the count for word""" if uniquewords.has_key(word): uniquewords[word] = uniquewords[word] + 1 else: uniquewords[word] = 1 mywords = dict() increment(mywords, "school") print mywords def increment(value): """increment the value???""" value = value + 1 myval = 5 increment(myval) print myval