You are on page 1of 4

Tuples_Lists_MutableObjects

Ibrahim Abou-Faycal

#
EECE-231
#
Introduction to Computation & Programming with Applications
#
Tuples & Lists - Mutable Objects

Reading: [Guttag, Sections 5.1, 5.2, and 5.3] Material in these slides is based on
• Slides of EECE-230C & EECE-230 MSFEA, AUB
• [Guttag, Chapter 5]

0.1 Lists and tuples with and without mutable objects


• List which does not contain mutable objects, e.g.,
L1 = [1, 20, 10]
• Tuple which does not contain mutable objects, e.g.,
T1 = (1, 20, 10)
• List containing mutable objects, e.g.,
L2 = [1, [3,6], 10]
• Tuple containing mutable objects, e.g.,
T2 = (1, [3,6], 10)

[ ]: L1 = [1, 20, 10]


T1 = (1, 20, 10)
L2 = [1, [3,6], 10]
T2 = (1, [3,6], 10)

Track it on http://www.pythontutor.com/visualize.html
• For a list L without mutable objects, assignment operator L2 = L creates an alias, and L2 =
L.copy() creates a clone

1
2
• For a tuple T without mutable objects, only need the assignment operator T2 = T since
anyways we cannot change T (there is no copy() member function associated with the type
tuple)
• For a list containing mutable objects, assignment operator L2 = L creates an alias, and L2 =
L.copy() creates a clone whose mutable objects are aliases
• For a tuple containing mutable objects, the assignment operator T2 = T creates an alias
• What if we are interested in a deep copy of a list or tuple containing mutable objects: clone
all mutable and immutable objects all the way (i.e., recursively)

0.2 Deep copy


Use the copy.deepcopy() function from the copy module
[ ]: from copy import deepcopy
L = [1, [3, 6], 10]
L1 = L
L2 = L.copy()
L3 = deepcopy(L2)
T = (1, [3, 6], 10)
T1 = T # Can't use T.copy()
T3 = deepcopy(T)

Track it on http://www.pythontutor.com/visualize.html

3
4

You might also like