130 likes | 146 Views
CSE 231 Lab 7. Topics to cover. Mutable List vs Immutable Tuples Shallow and deep copy operations LISTS and tuples in functions. Mutable List vs Immutable Tuples. List can be changed or modified whereas tuple can’t be changed or modified
E N D
Topics to cover Mutable List vs Immutable Tuples Shallow and deep copy operations LISTS and tuples in functions
Mutable List vs Immutable Tuples • List can be changed or modified whereas tuple can’t be changed or modified • Using a tuple instead of a list can give the programmer and the interpreter a hint that the data should not be changed. • List has more functionality than the tuple.
Shallow and deep copy operations • Shallow copy constructs a new object and then inserts references into it to the objects found in the original. In [3]: colours2[1] = "green“ In [4]: print(colours1) In [1]: colours1 = ["red", "blue"] In [2]: colours2 = colours1 ['red', 'green']
Shallow and deep copy operations In [1]: import copy In [2]: lst1 = ['a','b',['ab','ba']] In [3]: lst2 = copy.deepcopy(lst1) In [4]: lst2[2][1] = "d" In [5]: lst2[0] = "c“ • Deep copy constructs a new object and then, recursively, inserts copies into it of the objects found in the original.
Do these in PythonTutor.com L1 = ['a','b','c'] L2 = [1,L1,2] print(L2) L1[1] = 'X' print(L2) [1, ['a', 'b', 'c'], 2] [1, ['a', 'X', 'c'], 2] What is the output?
Do these in PythonTutor.com L3 = L2 L4 = L2[:] L1.append(100) print(L3) print(L4) What is the output? [1, ['a', 'X', 'c', 100], 2] [1, ['a', 'X', 'c', 100], 2]
Do these in PythonTutor.com True False print(L3 is L2) print(L4 is L2) L2.append('axe') print(L3) print(L4) What is the output? [1, ['a', 'X', 'c', 100], 2, 'axe'] [1, ['a', 'X', 'c', 100], 2]
Do these in PythonTutor.com import copy L5 = copy.deepcopy(L2) print(L5) print(L2) What is the output? [1, ['a', 'X', 'c', 100], 2, 'axe'] [1, ['a', 'X', 'c', 100], 2, 'axe']
Do these in PythonTutor.com L2.append(222) print(L5) print(L2) What is the output? [1, ['a', 'X', 'c', 100], 2, 'axe'] [1, ['a', 'X', 'c', 100], 2, 'axe', 222]
LISTS and tuples in functions defdoubleStuff(alist): for position in range(len(alist)): alist[position] = 2 * alist[position] things = [2, 5, 9] doubleStuff(things) print(things) lst= [2, 5, 9] doubleStuff(lst[:]) print(lst) [4, 10, 18] [2, 5, 9]
LISTS and tuples in functions defdoubleStuff(atuple): for position in range(len(atuple)): atuple[position] = 2 * atuple[position] things = (2, 5, 9) doubleStuff(things) print(things) TypeError: 'tuple' object does not support item assignment Tuple are immutable cannot be modified after creation
LISTS and tuples in functions defnewStuff(atuple): atuple=2*atuple things = (2, 5, 9) newStuff(things) print(things) (2, 5, 9)