PCEP-30-02 · Question #21
What is the expected output of the following code? ``python 1 data = () 2 print(data.__len__()) ``
The correct answer is C. 0. data = () creates an empty tuple - a tuple with zero elements. Calling .__len__() (the dunder method equivalent of len()) on it returns 0, making C correct. Why the distractors are wrong: A - The code is perfectly valid Python. Empty tuples are legal, and __len__() is a…
Question
1 data = ()
2 print(data.__len__())
Options
- AThe code is erroneous.
- B1
- C0
- DNone
How the community answered
(35 responses)- A11% (4)
- B3% (1)
- C80% (28)
- D6% (2)
Explanation
data = () creates an empty tuple - a tuple with zero elements. Calling .__len__() (the dunder method equivalent of len()) on it returns 0, making C correct.
Why the distractors are wrong:
- A - The code is perfectly valid Python. Empty tuples are legal, and
__len__()is a standard sequence method available on all tuples. - B -
1would only be returned if the tuple contained exactly one element, e.g.,data = (42,). - D -
__len__()always returns an integer, neverNone.Nonewould only appear if a function had noreturnstatement.
Memory tip: Think of () as an empty box - len() counts what's inside the box, and an empty box contains 0 items. The .__len__() syntax is just the explicit dunder form of len(data), so they're interchangeable on any sequence type.
Community Discussion
No community discussion yet for this question.