Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 231 Lab 7.

Similar presentations


Presentation on theme: "CSE 231 Lab 7."— Presentation transcript:

1 CSE 231 Lab 7

2 Topics to cover Mutable List vs Immutable Tuples
Shallow and deep copy operations LISTS and tuples in functions A Python list is a sequence of objects. It is a sequence like a string. It shares characteristics such as indexing & slicing, iteration (for) and membership (in) as well as functions such as len().

3 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.

4 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']

5 Shallow and deep copy operations
Deep copy constructs a new object and then, recursively, inserts copies into it of the objects found in the original. 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“

6 Do these in PythonTutor.com
L1 = ['a','b','c'] L2 = [1,L1,2] print(L2) L1[1] = 'X' [1, ['a', 'b', 'c'], 2] [1, ['a', 'X', 'c'], 2] What is the output?

7 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]

8 Do these in PythonTutor.com
print(L3 is L2) print(L4 is L2) L2.append('axe') print(L3) print(L4) True False What is the output? [1, ['a', 'X', 'c', 100], 2, 'axe'] [1, ['a', 'X', 'c', 100], 2]

9 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']

10 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]

11 LISTS and tuples in functions
def doubleStuff(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]

12 LISTS and tuples in functions
def doubleStuff(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

13 LISTS and tuples in functions
def newStuff(atuple): atuple=2*atuple things = (2, 5, 9) newStuff(things) print(things) (2, 5, 9)


Download ppt "CSE 231 Lab 7."

Similar presentations


Ads by Google