PCEP-30-02 practice question 27 of 35

What is the output of the following Python code? x = [1, 2, 3, 4, 5] result = len(x) print(result)

Full set: 548 questions

Domain Data Collections – Tuples, Dictionaries, Lists, and Strings

Answer options
A: [0, 1, 2, 3, 4]
B: [1, 2, 3, 4, 5]
C: 5 Correct answer
D: 15
Correct Answer:
C. 5
Explanation

The code initializes a list named x containing five integer elements. The len() built-in function is then called with x as its argument. This function returns the number of items in a container. For the list x, which has five elements (1, 2, 3, 4, 5), len(x) evaluates to the integer 5. This value is assigned to the variable result. Finally, the print() function outputs the value of result, which is 5.

Why Incorrect

A. [0, 1, 2, 3, 4] This is a list of indices for a five-element sequence. The len() function returns a single integer representing the total count of elements, not a list of their indices.
B. [1, 2, 3, 4, 5] This is the original list x. The code is designed to print the length of the list, which is an integer, not the list's contents.
D. 15 This is the sum of the elements in the list (1+2+3+4+5). The len() function counts the number of elements, whereas the sum() function would be used to calculate their total value. ---

References

1. Python Software Foundation. (2024). Built-in Functions — The Python Standard Library. Python 3.12.4 documentation.

Section: len(s)

Content: "Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set)." This confirms that len() on a list returns the count of its items.

2. Guttag, J. V. (2016). Introduction to Computation and Programming Using Python, With Application to Understanding Data (2nd ed.). MIT Press.

Chapter 5: Structured Types, Mutability, and Higher-Order Functions, Section 5.2 Lists and Mutability.

Content: The text describes lists and common operations, including len(), stating that it returns the number of elements in the list. This is a foundational concept covered in university-level Python programming courses.

3. University of Michigan. (n.d.). Python for Everybody: Exploring Data in Python 3.

Chapter 8: Lists, Section 8.3: Lists are Mutable.

Content: "The function len and the range function, when applied to a list, return the number of elements in the list." This courseware explicitly defines the behavior of len() with lists.

Scroll to Top