[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]]
  1. Solution: The first code fragment appends [4] to the list L, hence modifying it. Both L and M 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
  1. Solution: The second code fragment appends [49] to the list L and then returns its elements as a tuple. The list L is modified, and mi, m2, m3, and m4 receive the values of L‘s elements. The comparison between L[3] and m4 is true as they point to the same object.
"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *