ProgrammingVery hardTCS NQT · Infosys HackWithInfy · Product Company SDE
What does the following Python 3 code print? a = [1, 2, 3] b = a[:] b.append(4) print(a, b)
- A. [1, 2, 3] [1, 2, 3, 4]
- B. [1, 2, 3, 4] [1, 2, 3, 4]
- C. [1, 2, 3, 4] [1, 2, 3]
- D. [1, 2, 3] [1, 2, 3]
Correct answer: A. [1, 2, 3] [1, 2, 3, 4]
a[:] makes a shallow copy with a new outer list, so appending to b leaves the original a untouched.
More Python Programming questions
- What does the following Python 3 code print? def f(a, b, args): return a, b, args print(f(1, 2, 3, 4, 5))
- What does the following Python 3 code print? def f(kwargs): return sorted(kwargs.items()) print(f(b=2, a=1, c=3))
- What does the following Python 3 code print? def f(a, , b): return a + b try: print(f(1, 2)) except TypeError: print("err")
- What does the following Python 3 code print? l = [1, 2, 3] print(l, sep="-")
- What does the following Python 3 code print? print([1, 2, 3], [4, 5], sep=",")
- What does the following Python 3 code print? d = {"a": 1, "b": 2} print(d)