Question discussion

What is the output of the following Python code?d = {} d.setdefault('a', []).append(1) d.setdefault('a', []).append(2) d.setdefault('b', []…

2367Medium DSSSB TGT Computer Science 0 replies 1 views
0

What is the output of the following Python code?

d = {}
d.setdefault('a', []).append(1)
d.setdefault('a', []).append(2)
d.setdefault('b', []).append(3)
print(d)
  • A{'a': [1], 'b': [3]}
  • B{'a': [2], 'b': [3]}
  • C{'a': [1, 2], 'b': [3]}
  • D{'a': [1, 2, 3]}
Correct answer: C

Explanation

setdefault returns the existing list if the key is present and otherwise inserts the default, so 'a' collects 1 and 2 while 'b' gets its own list [3].

Discussion 0

Nobody has replied yet. Start the discussion!