Computer Science

What is the output of following code fragments ?

def increment(n):
    n.append([4])
    return n
L = [1, 2, 3]
M = increment(L)
print(L, M)

Python

Python Functions

2 Likes

Answer

[1, 2, 3, [4]] [1, 2, 3, [4]]

Working

In the code, the function increment appends [4] to list n, modifying it in place. When L = [1, 2, 3], calling increment(L) changes L to [1, 2, 3, [4]]. Variable M receives the same modified list [1, 2, 3, [4]], representing L. Thus, printing L and M results in [1, 2, 3, [4]], confirming they reference the same list. Therefore, modifications made to list inside a function affect the original list passed to the function.

Answered By

1 Like


Related Questions