[Type B] Working with Functions – Chapter 3 Sumita Arora
Table of Contents
18. What is the output of the following code fragments?
18. (i) Python
def increment(n):
n.append([4])
return n
L = [1, 2, 3]
M = increment(L)
print(L, M)
Output
[1, 2, 3, [4]] [1, 2, 3, [4]]
- Solution: The first code fragment appends
[4]
to the listL
, hence modifying it. BothL
andM
point to the same modified list.
18. (ii) Python
def increment(n):
n.append([49])
return n[0], n[1], n[2], n[3]
L = [23, 35, 47]
mi, m2, m3, m4 = increment(L)
print(L)
print(mi, m2, m3, m4)
print(L[3] == m4)
Output
[23, 35, 47, [49]]
23 35 47 [49]
True
- Solution: The second code fragment appends
[49]
to the listL
and then returns its elements as a tuple. The listL
is modified, andmi
,m2
,m3
, andm4
receive the values ofL
‘s elements. The comparison betweenL[3]
andm4
is true as they point to the same object.