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)
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.
Related Questions
Write a program with a function that takes an integer and prints the number that follows after it. Call the function with these arguments :
4, 6, 8, 2 + 1, 4 - 3 * 2, -3 -2
Write a program with non-void version of above function and then write flow of execution for both the programs.
What is the output of following code fragments ?
def increment(n): n.append([49]) return n[0], n[1], n[2], n[3] L = [23, 35, 47] m1, m2, m3, m4 = increment(L) print(L) print(m1, m2, m3, m4) print(L[3] == m4)
What will be the output of the following Python code ?
V = 25 def Fun(Ch): V = 50 print(V, end = Ch) V *= 2 print(V, end = Ch) print(V, end = "*") Fun("!") print(V)
- 25*50!100!25
- 50*100!100!100
- 25*50!100!100
- Error