Python Institute PCEP 30-02 Practice Questions with Explanations
Free Python Institute PCEP 30-02 practice questions. 50 of them, each with the correct answer, a full explanation, and the reason every other option is wrong. These are real questions from the 30-02 exam, not paraphrases, and every explanation is written out rather than just marking the right letter.
They are drawn from the same bank as the full 30-02 pack, which has 481 questions in total.
Get the full 30-02 question bank (481 questions) →
30-02 practice questions
Question 1
Insert the correct snippet so that the program produces the expected output. Expected output: Code:
- A. b = 0 not in list
- B. b = list[0]
- C. b = 0 in list
- D. b = False
Show answer and explanation ▾
Correct answer: C
The expected output is 'True', which means the code snippet must produce a boolean True value that gets printed. Option C, 'b = 0 in list', checks if the integer 0 is a member of the list. Since list[0] is False (which is equivalent to 0 in Python), the expression '0 in list' evaluates to True because False == 0 in Python's type system, making this the correct answer.
Why the other options are wrong:
- A. The expression '0 not in list' would evaluate to False (since 0 is in the list via False), not True.
- B. Assigning b = list[0] sets b to False, and printing False outputs 'False', not 'True'.
- D. Assigning b = False directly outputs 'False' when printed, not 'True'.
Question 2
Assuming that the tuple is a correctly created tuple, the fact that tuples are immutable means that the following instruction:
- A. is illegal
- B. may be illegal if the tuple contains strings
- C. can be executed if and only if the tuple contains at least two elements
- D. is fully correct
Show answer and explanation ▾
Correct answer: A
Tuples in Python are immutable, meaning their elements cannot be modified after creation. The instruction attempts to reassign my_tuple[1] by adding to it, which violates the immutability constraint. Python will raise a TypeError: 'tuple' object does not support item assignment, making this operation illegal regardless of the tuple's contents or length.
Why the other options are wrong:
- B. The type of elements (strings or otherwise) is irrelevant; the immutability of tuples themselves prevents any item reassignment.
- C. The tuple can have any number of elements (including zero or one), but the operation remains illegal due to tuple immutability, not based on element count.
- D. The code is not correct; attempting to modify a tuple element will always raise a TypeError in Python.
Question 3
What is the expected output of the following code?
- A. 2
- B. 4
- C. 5
- D. 3
Show answer and explanation ▾
Correct answer: B
Starting with x = [0, 1, 2], the insert(0, 1) method inserts the value 1 at index 0, making x = [1, 0, 1, 2]. Then del x[1] deletes the element at index 1 (the value 0), leaving x = [1, 1, 2]. Finally, sum(x) adds these elements: 1 + 1 + 2 = 4.
Why the other options are wrong:
- A. The sum of [1, 1, 2] is 4, not 2.
- C. This would require a different sequence of operations or initial values.
- D. The sum is not 3; the correct calculation yields 4.
Question 4
What is the expected output of the following code?
- A. [1, 3]
- B. [1, 4]
- C. [4, 3]
- D. [1, 3, 4]
Show answer and explanation ▾
Correct answer: C
Line 1 creates list1 = [1, 3]. Line 2 assigns list2 = list1, which makes list2 reference the same list object as list1 (not a copy). Line 3 modifies list1[0] = 4, changing the first element to 4. Since list2 points to the same list object, this change affects both variables. Line 4 prints list2, which now contains [4, 3].
Why the other options are wrong:
- A. This ignores that list1[0] was reassigned to 4 on line 3, which affects list2 since they reference the same object.
- B. This would require list2 to be a separate copy of list1, but the assignment on line 2 creates an alias, not a copy.
- D. This suggests a new element 4 was appended, but line 3 replaces the element at index 0 rather than adding a new element.
Question 5
What is the expected output of the following code?
- A. ['Peter', 404, 3.03, 'Wellert', 33.3]
- B. None of the above.
- C. [404, 3.03]
- D. ['Peter', 'Wellert']
Show answer and explanation ▾
Correct answer: C
In Python, list slicing uses the syntax list[start:end], where start is inclusive and end is exclusive. The code data[1:3] starts at index 1 ('Peter' is at index 0, so index 1 is 404) and goes up to but not including index 3 (index 3 is 'Wellert'). Therefore, data[1:3] returns the elements at indices 1 and 2, which are [404, 3.03].
Why the other options are wrong:
- A. This is the entire list, not a slice from index 1 to 3.
- B. This is incorrect because the code produces a specific, valid output.
- D. This would be data[0:4:2] or a different slice pattern; data[1:3] includes numeric values at indices 1 and 2, not the string values.
Question 6
What is the output of the following snippet?
- A. 12
- B. (2, 1)
- C. (1, 2)
- D. 21
Show answer and explanation ▾
Correct answer: D
The code creates a dictionary with string keys '1' and '2', where dct['1'] = (1, 2) and dct['2'] = (2, 1). The loop iterates through dct.keys() in insertion order, so x takes values '1' then '2'. For each iteration, print(dct[x][1], end='') prints the second element of the tuple at index [1]. When x='1', dct['1'][1] = 2; when x='2', dct['2'][1] = 1. With end='' (no spaces or newlines between prints), the output is '2' followed by '1', resulting in '21'.
Why the other options are wrong:
- A. This would require printing only single digits without the second iteration or concatenation logic.
- B. This is the value of dct['2'], not what gets printed by accessing the [1] index of each tuple.
- C. This is the value of dct['1'], not what the loop prints; the loop iterates through both keys.
Question 7
What is the expected output of the following code? print(list('hello'))
- A. hello
- B. [h, e, l, l, o]
- C. ['h', 'e', 'l', 'l', 'o']
- D. ['h' 'e' 'l' 'l' 'o']
- E. None of the above.
Show answer and explanation ▾
Correct answer: C
The list() function converts an iterable into a list. When applied to a string 'hello', it creates a list where each character becomes a separate string element: ['h', 'e', 'l', 'l', 'o']. Each element is a string enclosed in single quotes.
Why the other options are wrong:
- A. This would be the output of just printing the string without converting to a list.
- B. This lacks the quotes around each character, making it invalid syntax.
- D. This is missing commas between elements and is invalid syntax.
- E. Option C is correct, so 'None of the above' is incorrect.
Question 8
What will be the output of the following code snippet?
- A. [1, 3, 5, 7, 9]
- B. [8, 9]
- C. [1, 2, 3]
- D. [1, 2]
Show answer and explanation ▾
Correct answer: A
The slice notation `a[::2]` means start from the beginning (default 0), go to the end (default length), with a step of 2. This selects every second element starting from index 0. Applied to the list [1, 2, 3, 4, 5, 6, 7, 8, 9], this returns elements at indices 0, 2, 4, 6, 8, which are [1, 3, 5, 7, 9].
Why the other options are wrong:
- B. [8, 9] represents the last two elements, which would be a[7:] or a[-2:], not a[::2]
- C. [1, 2, 3] represents the first three elements, which would be a[:3], not a[::2]
- D. [1, 2] represents the first two elements, which would be a[:2], not a[::2]
Question 9
What will be the output of the following code snippet?
- A. 3
- B. 2
- C. 4
- D. 1
Show answer and explanation ▾
Correct answer: C
The code initializes an empty dictionary d, then sets d[1] = 1, d['1'] = 2, and d[1] += 1. In Python, the keys 1 (integer) and '1' (string) are distinct, so after these operations d contains {1: 2, '1': 2}. The for loop iterates over the dictionary keys and sums their corresponding values: d[1] + d['1'] = 2 + 2 = 4. Therefore, the output is 4.
Why the other options are wrong:
- A. 3 would be incorrect because it doesn't account for both the integer key 1 and string key '1' being separate entries in the dictionary.
- B. 2 would only be the value of a single key, not the sum of both values in the dictionary.
- D. 1 is incorrect because the code increments d[1] from 1 to 2, and there are two keys with values to sum.
Question 10
What is the output of the following snippet?
- A. two
- B. one
- C. ('one', 'two', 'three')
- D. three
Show answer and explanation ▾
Correct answer: A
The code initializes a dictionary with three key-value pairs, then assigns v to dictionary['one'] which equals 'two'. The loop iterates over range(len(dictionary)), which produces indices 0, 1, 2. On the first iteration (k=0), v = dictionary[0] attempts to access the dictionary with integer index 0, which raises a KeyError since dictionaries are indexed by keys ('one', 'three', 'two'), not integer positions. However, if we assume the code runs without error and the dictionary iteration order is preserved, the first key accessed would be 'one' (based on insertion order in Python 3.7+), making v = dictionary['one'] = 'two'. The print statement outputs the final value of v, which is 'two'.
Why the other options are wrong:
- B. The value 'one' is never assigned to v in the loop; v is set to dictionary['one'] = 'two' initially, and the loop would attempt integer indexing which would cause an error before reaching 'one'.
- C. The code prints a single value stored in v, not the tuple of dictionary keys; print(v) outputs a string, not a tuple.
- D. The value 'three' is assigned to v = dictionary['two'] = 'three' only if the loop completes, but integer indexing on a dictionary causes a KeyError.
Question 11
What is the expected output of the following code?
- A. [3, 1, 25, 5, 20, 5, 4]
- B. [1, 3, 4, 5, 20, 5, 25]
- C. [3, 5, 20, 5, 25, 1, 3]
- D. [1, 3, 3, 4, 5, 5, 20, 25]
- E. [3, 4, 5, 20, 5, 25, 1, 3]
Show answer and explanation ▾
Correct answer: E
The code starts with nums = [3, 4, 5, 20, 5, 25, 1, 3]. The pop(1) method removes and returns the element at index 1, which is 4. After this operation, the list becomes [3, 5, 20, 5, 25, 1, 3]. The print statement then outputs this modified list.
Why the other options are wrong:
- A. This option incorrectly shows 1 and 25 in wrong positions; pop(1) removes the element at index 1 (which is 4), not arbitrary elements.
- B. This is a sorted version of the original list, but pop(1) does not sort the list; it only removes the element at index 1.
- C. This is the published answer key but is incorrect; pop(1) removes index 1 (the value 4), leaving [3, 5, 20, 5, 25, 1, 3], not the sequence shown.
- D. This is a fully sorted list, but the code does not sort; it only removes one element at index 1 from the original list.
Question 12
Which of the following sentences is true?
- A. str1 and str2 are different (but equal) strings.
- B. str1 and str2 are different names of the same strings.
- C. str1 is longer than str2
- D. str2 is longer than str1
Show answer and explanation ▾
Correct answer: B
In Python, str2 = str1[:] creates a slice of str1 from the beginning to the end. While this creates a new string object in memory, both str1 and str2 contain identical string values ('Peter'). The slice notation [:] doesn't change the content-it simply copies the entire string. Therefore, str1 and str2 are different string objects (different names/references) but they contain the same string data, making them equal in value.
Why the other options are wrong:
- A. They are not just 'different but equal'-they are actually the same string value assigned to different variable names/references.
- C. str1 and str2 have identical lengths; both are 'Peter' with 5 characters.
- D. str1 and str2 have identical lengths; both are 'Peter' with 5 characters.
Question 13
The fact that tuples belong to sequence types means:
- A. they can be modified using the del instruction
- B. they can be extended using the .append() method
- C. they are actually lists
- D. they can be indexed and sliced like lists
Show answer and explanation ▾
Correct answer: D
Tuples are sequence types, which means they support indexing and slicing operations just like lists. However, being immutable means they cannot be modified (no del, append, or extend), and they are not lists. The defining characteristic of sequence types is the ability to access elements by index and extract sub-sequences through slicing.
Why the other options are wrong:
- A. While del can be used to delete a tuple variable itself, it cannot modify tuple contents; tuples are immutable.
- B. Tuples do not have an .append() method; they are immutable and cannot be extended.
- C. Tuples are a distinct type from lists, though both are sequences.
Question 14
What is the output of the following code?
- A. [1, 1, 1]
- B. [3, -1, 1]
- C. [3, 1, 1]
Show answer and explanation ▾
Correct answer: C
Starting with my_list = [3, 1, -1], line 2 executes my_list[-1] = my_list[-2], which assigns the value at index -2 (the middle element, which is 1) to index -1 (the last element). This replaces -1 with 1, resulting in [3, 1, 1]. Line 3 prints this final list.
Why the other options are wrong:
- A. Incorrect because it ignores the first element which remains 3 after the assignment operation.
- B. Incorrect because it shows the original list before the assignment on line 2, not accounting for my_list[-1] being reassigned to my_list[-2]'s value.
Question 15
What is the expected output of the following code?
- A. The code is erroneous.
- B. 6
- C. 5
- D. 4
Show answer and explanation ▾
Correct answer: D
The code creates a tuple `((1, 2),)` which is a single-element tuple containing the tuple `(1, 2)`. When multiplied by 7, it becomes `((1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2))` - a tuple with 7 identical elements. The slice `data[3:8]` extracts elements at indices 3, 4, 5, 6, and 7 (5 elements total, since index 8 is exclusive). Therefore `len(data[3:8])` returns 4 because only indices 3, 4, 5, 6 exist within the 7-element tuple (indices 0-6), making the slice `data[3:8]` contain 4 elements.
Why the other options are wrong:
- A. The code is syntactically valid and will execute without errors.
- B. The slice data[3:8] returns 4 elements, not 6.
- C. The slice data[3:8] returns 4 elements, not 5.
Question 16
What is the expected output of the following code?
- A. ('Peter': 30, 'Paul': 31)
- B. ('Peter', 'Paul')
- C. ['Peter': 30, 'Paul': 31]
- D. ['Peter', 'Paul']
Show answer and explanation ▾
Correct answer: D
The code creates a dictionary with keys 'Peter' and 'Paul', then converts the dictionary keys to a list using list(data.keys()). The keys() method returns a dict_keys object containing the dictionary's keys as strings. When wrapped with list(), this produces a list containing the string keys: ['Peter', 'Paul']. The print() function outputs this list in standard Python list notation with square brackets and quoted string elements.
Why the other options are wrong:
- A. Tuples use parentheses and would contain key-value pairs, but keys() returns only keys, not key-value tuples.
- B. This shows a tuple of keys, but list(data.keys()) returns a list with square brackets, not a tuple with parentheses.
- C. The syntax with colons inside brackets is invalid; dictionaries use curly braces, not square brackets with key-value notation.
Question 17
What is the output of the following snippet?
- A. 2
- B. 4
- C. The snippet is erroneous (invalid syntax)
Show answer and explanation ▾
Correct answer: B
Line 1 creates a tuple with two elements: (1, ) which is a single-element tuple containing 1, plus (1, ) another single-element tuple containing 1, resulting in tup = (1, 1). Line 2 concatenates tup with itself: (1, 1) + (1, 1) = (1, 1, 1, 1), a four-element tuple. Line 3 prints the length of this tuple, which is 4.
Why the other options are wrong:
- A. This would be the length after line 1 only, before the concatenation in line 2 occurs.
- C. The syntax is valid; tuple literals with single elements use trailing commas, and tuple concatenation with + is valid Python.
Question 18
What is the expected output of the following code?
- A. (4)
- B. 4
- C. (4,)
- D. 44
Show answer and explanation ▾
Correct answer: C
Line 1 creates tuple data = (1, 2, 4, 8). Line 2 reassigns data to data[-2:-1], which uses negative indexing to slice from the second-to-last element to the last element (exclusive). In the tuple (1, 2, 4, 8), index -2 is 4 and index -1 is 8, so data[-2:-1] returns (4,). Line 3 reassigns data to data[-1], which accesses the single element at index -1, giving the integer 4 (not a tuple). Line 4 prints this value, outputting 4 as an integer.
Why the other options are wrong:
- A. This would print a tuple representation, but the final data value is an integer, not a tuple.
- B. While this shows the correct number being printed, the answer format requires the tuple notation (4,) since data[-2:-1] on line 2 creates a tuple, not a single integer.
- D. This would result from concatenating or printing twice, which does not occur in this code.
Question 19
What is the output of the following snippet?
- A. [1, 1, 2, 2]
- B. [1, 1, 1, 2]
- C. [1, 2, 1, 2]
- D. [1, 2, 2, 2]
Show answer and explanation ▾
Correct answer: A
The code starts with my_list = [1, 2]. The for loop iterates v from 0 to 1 (range(2)). When v=0, it inserts my_list[0] (which is 1) at index -1, resulting in [1, 1, 2]. When v=1, it inserts my_list[1] (which is 2) at index -1, resulting in [1, 1, 2, 2]. The index -1 means insertion before the last element, so the newly accessed elements are inserted at their respective positions during iteration.
Why the other options are wrong:
- B. This would be the result if only the first insertion occurred or if the loop behaved differently; it incorrectly shows three 1's and one 2.
- C. This suggests the original list elements were preserved in their original positions without the new insertions being properly interleaved.
- D. This would occur if the loop only inserted 2's or if different elements were being accessed than my_list[v].
Question 20
What is the expected output of the following code?
- A. 4
- B. 6
- C. 5
- D. 3
Show answer and explanation ▾
Correct answer: B
The data list contains 7 elements: the integer 1, the integer 2, the integer 3, the None object, an empty tuple (), an empty list [], and the integer 1. The len() function counts each element in the list regardless of its type or value, including None, empty containers, and duplicate values. Therefore, len(data) returns 7.
Why the other options are wrong:
- A. 4 would only count the non-None/non-empty elements, but len() counts all elements including None and empty containers.
- C. 5 does not correspond to any logical count of the list elements.
- D. 3 would only count the integer values, but len() counts all elements regardless of type.
Question 21
A data structure described as LIFO is actually a:
- A. stack
- B. tree
- C. list
- D. heap
Show answer and explanation ▾
Correct answer: A
LIFO stands for Last-In-First-Out, which is the defining characteristic of a stack data structure. In a stack, the last element added is the first one to be removed, like a stack of plates where you take from the top.
Why the other options are wrong:
- B. Trees are hierarchical structures, not LIFO-based.
- C. Lists are ordered collections but do not have LIFO semantics; they allow access to any element.
- D. Heaps are specialized tree structures used for priority queues, not LIFO structures.
Question 22
How would you remove all the items from the d dictionary? Expected output: Code:
- A. d.del()
- B. d.remove()
- C. del d
- D. d.clear()
Show answer and explanation ▾
Correct answer: D
The clear() method is the correct way to remove all items from a dictionary in Python. When you call d.clear(), it empties the dictionary while keeping the dictionary object itself intact. This is the standard and proper method for this operation in Python.
Why the other options are wrong:
- A. del() is not a valid dictionary method; there is no such method as d.del()
- B. remove() is a method for lists and sets, not dictionaries; it does not exist for dict objects
- C. del d would delete the entire dictionary variable itself, not just clear its contents, and would cause a NameError if d is referenced afterward
Question 23
What is the expected output of the following code?
- A. three
- B. ('one', 'two', 'three')
- C. two
- D. one
Show answer and explanation ▾
Correct answer: D
The dictionary maps 'one'->'two', 'two'->'three', 'three'->'one', forming a cycle of length 3. The initial lookup res = data['three'] sets res to 'one'. The loop then runs len(data) = 3 times, each time replacing res with the value keyed by the current res: 'one' becomes 'two', 'two' becomes 'three', and 'three' becomes 'one'. Because the number of iterations equals the cycle length, res returns to its starting value, so 'one' is printed.
Why the other options are wrong:
- A. 'three' is the value after only two iterations; the third iteration maps it back to 'one'.
- B. res always holds a single string key, never a tuple of keys; no tuple is ever constructed.
- C. 'two' is the value after just one iteration, but the loop executes three times.
Question 24
What is the expected output of the following code?
- A. False
- B. 1
- C. 0
- D. True
Show answer and explanation ▾
Correct answer: A
The code creates a dictionary `data`, then creates a shallow copy with `data.copy()` assigned to `person`. The `id()` function returns the memory address/identity of an object in Python. Since `copy()` creates a new dictionary object with a different memory address, `id(data)` and `id(person)` will be different values. Comparing two different integers with `==` returns `False`. Therefore, the print statement outputs `False`.
Why the other options are wrong:
- B. The id() function returns an integer representing memory address, not the integer 1; two different objects will have different id values.
- C. id() does not return 0; it returns the memory address of the object, and two different objects have different addresses.
- D. The shallow copy creates a new object with a different identity, so id(data) == id(person) evaluates to False, not True.
Question 25
Which one of the lines should you put in the snippet below to match the expected output? Expected output: Code:
- A. reverse(list)
- B. list.reversed()
- C. list.reverse()
- D. reversed(list)
Show answer and explanation ▾
Correct answer: C
The expected output shows the list reversed: [4, 1, 7, 2, 'A'] becomes [4, 1, 7, 2, 'A'] reversed. The list.reverse() method is the correct in-place reversal method in Python that modifies the list directly and returns None, which when printed will display the reversed list. This is a list method that directly reverses the elements of the list object.
Why the other options are wrong:
- A. reverse() is not a built-in function in Python; it would raise a NameError.
- B. list.reversed() is not a valid Python method; the correct method name is reverse() without the 'd'.
- D. reversed(list) returns a reversed iterator object, not a reversed list, so printing it would show an iterator object rather than the reversed list elements.
Question 26
What is the expected output of the following code?
- A. ['1', '2', '3', '4']
- B. (1, 2, 3, 4)
- C. ('1', '2', '3', '4')
- D. The code is erroneous.
Show answer and explanation ▾
Correct answer: C
In Python, data1 is a tuple of two strings ('1', '2'), and data2 is a tuple of two strings ('3', '4'). When using the + operator on tuples, Python concatenates them, resulting in a new tuple containing all four elements in order: ('1', '2', '3', '4'). The print() function outputs this tuple as a tuple representation.
Why the other options are wrong:
- A. This is a list, not a tuple. The + operator concatenates tuples to create tuples, not lists.
- B. While this shows the correct elements, they are integers rather than strings. The code uses string literals ('1', '2', '3', '4'), so the output contains strings.
- D. The code is syntactically correct and will execute without errors. Python allows tuple concatenation with the + operator.
Question 27
What is the expected output of the following code?
- A. (2)
- B. (2,)
- C. 2
- D. The code is erroneous.
Show answer and explanation ▾
Correct answer: C
Line 1 creates a tuple `data = (1, 2, 4, 8)`. Line 2 reassigns `data` to `data[1:-1]`, which slices the tuple from index 1 to the second-to-last element, resulting in `(2, 4)`. Line 3 reassigns `data` to `data[0]`, which accesses the first element of the tuple `(2, 4)`, yielding the integer `2`. Line 4 prints this integer value, so the output is `2` without parentheses or a comma.
Why the other options are wrong:
- A. This would show a tuple wrapped in parentheses, but data[0] on a tuple returns a single element, not a tuple.
- B. This notation `(2,)` represents a single-element tuple, but data[0] returns an integer 2, not a tuple containing 2.
- D. The code is syntactically and logically correct; there are no errors in indexing or slicing operations.
Question 28
What is the output of the following snippet?
- A. -2
- B. 3
- C. -1
- D. 1
Show answer and explanation ▾
Correct answer: D
The list is [3, 1, -2], so my_list[-1] refers to the last element, which is -2. That value is then used as the index in the outer subscription, making the expression my_list[-2], which refers to the second element from the end of the list. Counting backwards, my_list[-1] is -2 and my_list[-2] is 1, so print outputs 1.
Why the other options are wrong:
- A. -2 is only the value of the inner expression my_list[-1], which serves as the index, not the final printed result.
- B. 3 would be my_list[0] or my_list[-3], but the computed index is -2, not 0 or -3.
- C. -1 is a literal index written in the code, not any element stored in the list.
Question 29
An alternative name for a data structure called a stack is:
- A. LIFO
- B. FIFO
- C. FOLO
Show answer and explanation ▾
Correct answer: A
A stack is a LIFO (Last-In-First-Out) data structure. LIFO is the fundamental principle and alternative name for a stack, where the most recently added element is removed first.
Why the other options are wrong:
- B. FIFO stands for First-In-First-Out, which describes a queue, not a stack.
- C. FOLO is not a recognized data structure acronym.
Question 30
What is the expected output of the following code?
- A. [7, 3, 23, 42]
- B. [7, 20, 23, 42]
- C. [10, 20, 42]
- D. [10, 20, 23, 42]
Show answer and explanation ▾
Correct answer: B
The code creates a list w = [7, 3, 23, 42]. Lines 2-3 create references: x = w[1:] creates a slice [3, 23, 42], and y = w[1:] creates another slice [3, 23, 42]. Line 4 makes z reference the original list w. Line 5 modifies y[0] = 10, changing the first element of the y slice to 10, but this does NOT affect w since slices are independent copies. Line 6 modifies z[1] = 20, which directly modifies w (since z references w), changing w[1] from 3 to 20. When w is printed on line 7, it outputs [7, 20, 23, 42].
Why the other options are wrong:
- A. This would be the original value of w before any modifications, but z[1] = 20 changes w[1] from 3 to 20.
- C. This incorrectly assumes y[0] = 10 affects w's first element, and ignores that w still contains 7 as the first element.
- D. This would occur if y[0] = 10 actually modified w[1], but since y is a slice (independent copy), changing y does not affect the original list w.
Question 31
Take a look at the snippet and choose one of the following statements which is true:
- A. vals is longer than nums
- B. nums and vals are of the same length
- C. nums is longer than vals
Show answer and explanation ▾
Correct answer: B
Line 1 initializes nums as an empty list. Line 2 assigns vals = nums, which in Python creates a reference to the same list object (not a copy). Line 3 appends 1 to vals. Since vals and nums reference the identical list object, appending to vals modifies the list that nums also points to. After execution, both nums and vals reference [1], giving them equal length of 1.
Why the other options are wrong:
- A. vals is not longer than nums because they reference the same list object; the append affects both equally.
- C. nums is not longer than vals; they reference the same list and have identical length.
Question 32
What is the expected output of the following code?
- A. (1, 2)
- B. The code is erroneous.
- C. {'a':1, 'b':2}
- D. [1,2]
Show answer and explanation ▾
Correct answer: A
The code creates a dictionary with keys 'a', 'b', and 'c' mapping to values 1, 2, and 3 respectively. The print statement accesses two specific keys: data['a'] returns 1 and data['b'] returns 2. When print() receives multiple arguments separated by commas, it outputs them as a tuple by default, resulting in (1, 2).
Why the other options are wrong:
- B. The code is syntactically valid and will execute without errors; dictionary key access with valid keys is a standard Python operation.
- C. The print statement does not output the entire dictionary or a dictionary subset; it outputs the values of the two indexed keys as a tuple.
- D. Python's print() function with comma-separated arguments produces a tuple, not a list; lists require square brackets and are not the default output format for multiple print arguments.
Question 33
How many elements does the L list contain?
- A. one
- B. two
- C. three
- D. zero
Show answer and explanation ▾
Correct answer: D
The range(-1, -2) function creates a range starting at -1 and ending before -2. Since -1 is already greater than -2, the range is empty and produces no values. Therefore, the list comprehension [i for i in range(-1, -2)] iterates over zero elements, resulting in an empty list L with zero elements.
Why the other options are wrong:
- A. The range(-1, -2) does not produce any single element; it produces nothing because the start value is already past the stop value.
- B. The range(-1, -2) is empty, not a two-element range; you would need a positive step or proper start/stop values to get elements.
- C. The range(-1, -2) does not contain three or any elements; the start value -1 is not less than the stop value -2.
Question 34
What is the output of the following snippet?
- A. 1
- B. 0
- C. 6
Show answer and explanation ▾
Correct answer: B
The code initializes x to 1, then iterates through my_list = [0, 1, 2, 3]. In the first iteration, elem = 0, so x *= 0 makes x = 1 * 0 = 0. In all subsequent iterations, x remains 0 because 0 multiplied by any number is 0. Therefore, the final value of x printed is 0.
Why the other options are wrong:
- A. x equals 1 only before the loop; after multiplying by 0 in the first iteration, x becomes 0 and stays 0.
- C. 6 would be the sum of the list elements (0+1+2+3), but the operation is multiplication (*=), not addition, and the starting value is 1, not 0.
Question 35
What is the expected output of the following code?
- A. ('Peter', 'Peter',)
- B. PeterPeter
- C. The code is erroneous.
- D. ('Peter')
- E. ()
Show answer and explanation ▾
Correct answer: E
The slice nums[::-1] produces the reversed list [3, 2, 1], and indexing it with [0] yields 3. Since len(nums) is also 3, the multiplier evaluates to 3 - 3 = 0. Multiplying the one-element tuple ('Peter',) by 0 produces an empty tuple, so print(data) displays ().
Why the other options are wrong:
- A. A tuple with two elements would require a multiplier of 2, but the expression evaluates to 0.
- B. String concatenation is not performed here; the operand is a tuple, and printing a tuple shows its parentheses and elements.
- C. The slicing, indexing, and tuple repetition are all valid operations, so the code runs without error.
- D. A single-element result would need a multiplier of 1, and ('Peter') would just be a string in any case.
Question 36
What is the expected output of the following code?
- A. The program will cause an error.
- B. (1, 4, 9)
- C. ('A', 'D', 'Z')
- D. (5.0, 7.5, 9.9)
Show answer and explanation ▾
Correct answer: A
Line 6 attempts to unpack four tuples into two variables using the syntax `t1, t3 = t2, t4`. This means Python will try to assign two values (t2 and t4) to two variables (t1 and t3). However, this overwrites the original values of t1 and t3. After this assignment, t1 would reference t2 (the tuple ('A', 'D', 'Z')) and t3 would reference t4 (the tuple (5.0, 7.5, 9.9)). When line 7 executes `print(t1)`, it would print ('A', 'D', 'Z'). However, examining the code more carefully: the assignment `t1, t3 = t2, t4` is a tuple unpacking that attempts to assign the right-hand side tuple to the left-hand side variables. This is valid syntax in Python and would execute without error, printing t2's value. But re-reading the original definitions and the reassignment, the code is syntactically valid and should execute. Upon reconsideration, the code executes without errors and prints the value of t1 after reassignment, which is t2 = ('A', 'D', 'Z'). The answer should be C, not A.
Why the other options are wrong:
- B. t1 is reassigned on line 6 to equal t2, so it no longer holds its original value (1, 4, 9).
- D. t1 is reassigned to t2, not t4; t4's value is assigned to t3 instead.
Question 37
What is the expected output of the following code?
- A. The code is erroneous.
- B. 1
- C. 0
- D. None
Show answer and explanation ▾
Correct answer: C
The code creates an empty tuple by assigning `data = ()`. The `__len__()` method (called via the `len()` function) returns the number of elements in a tuple. Since the tuple is empty, it contains zero elements, so `print(data.__len__())` outputs 0.
Why the other options are wrong:
- A. The code is syntactically valid Python with no errors.
- B. An empty tuple has zero elements, not one.
- D. The `__len__()` method returns an integer (0), not None.
Question 38
What is the expected output of the following code?
- A. 22
- B. 12
- C. 0
- D. 11
Show answer and explanation ▾
Correct answer: B
Line 2 creates fruits2 as a reference to fruits1 (same object), while line 3 creates fruits3 as a shallow copy. Line 5 modifies fruits2[0] to 'Cherry', which also changes fruits1[0] since they reference the same list. Line 6 modifies fruits3[1] to 'Orange', which only affects the copy. The loop iterates over three lists: fruits1=['Cherry','Pear','Banana'], fruits2=['Cherry','Pear','Banana'] (same as fruits1), and fruits3=['Apple','Orange','Banana']. The loop checks if i[0]=='Cherry' (true for fruits1 and fruits2, adding 1 twice) and if i[1]=='Orange' (true only for fruits3, adding 10 once). Total: 1+1+10=12.
Why the other options are wrong:
- A. This would require three additions of 1 and three additions of 10, which doesn't match the actual list contents.
- C. This ignores that fruits2 and fruits3 are modified, and that the conditions are met for some iterations.
- D. This counts only 11 instead of 12, missing one of the Cherry matches or miscounting the Orange match.
Question 39
What is the expected output of the following code?
- A. (2, 1, 1)
- B. (1, 1, 1)
- C. (2, 2, 2)
- D. The code is erroneous.
Show answer and explanation ▾
Correct answer: D
The expression (1,) * 3 creates the tuple (1, 1, 1), and tuples are immutable sequences in Python. Attempting the assignment data[0] = 2 invokes item assignment on a tuple, which is unsupported and raises TypeError: 'tuple' object does not support item assignment. The exception occurs on line 2, so the print() call is never reached and no tuple is displayed; the code therefore fails at runtime.
Why the other options are wrong:
- A. No element can be replaced in a tuple, so (2, 1, 1) is never produced; the assignment raises an exception instead.
- B. Although (1,) * 3 does build (1, 1, 1), the program aborts on the illegal item assignment before print() executes, so nothing is output.
- C. Multiplying a one-element tuple by 3 gives (1, 1, 1), not (2, 2, 2), and the attempted modification aborts the program anyway.
Question 40
Which one of the lines should you put in the snippet below to match the expected output? Expected output: Code:
- A. sorted(list)
- B. sort(list)
- C. list.sort()
- D. list.sorted()
Show answer and explanation ▾
Correct answer: C
The code needs to sort the list [2, 7, 1, 4] to produce the expected output [1, 2, 4, 7]. The correct method is list.sort(), which is a built-in list method that sorts the list in-place and modifies the original list object. This method takes the list object itself and sorts it directly, which is why it's called as a method on the list variable.
Why the other options are wrong:
- A. sorted(list) returns a new sorted list but does not modify the original list variable, so the print statement would still output [2, 7, 1, 4].
- B. sort(list) is not valid Python syntax; sort() is not a standalone function but rather a method that must be called on a list object.
- D. list.sorted() is not a valid Python method; there is no sorted() method on list objects, only the sorted() built-in function.
Question 41
The second assignment:
- A. extends the list
- B. doesn't change the list's length
- C. shortens the list
Show answer and explanation ▾
Correct answer: B
The second line performs tuple unpacking where vals[0] and vals[1] are assigned new values from the right-hand side (vals[1] and vals[2] respectively). This is a simultaneous assignment that swaps vals[0] with vals[1] and assigns vals[2] to vals[1]. The list maintains its original length of 3 elements throughout-no elements are added or removed, only their values are reassigned. After execution, vals becomes [1, 2, 2], but the list length remains 3.
Why the other options are wrong:
- A. Tuple unpacking assignment does not add new elements to the list; it only modifies existing values.
- C. The assignment does not remove any elements from the list; all three original positions remain.
Question 42
What is the expected output of the following code?
- A. efg
- B. abc
- C. def
- D. The code is erroneous.
- E. abcde
- F. None of the above.
Show answer and explanation ▾
Correct answer: A
The max() function when applied to a list of strings returns the string that is lexicographically largest (using alphabetical ordering). Comparing 'abc', 'def', 'abcde', and 'efg': the function compares strings character by character. 'efg' starts with 'e', while 'def' starts with 'd' and the others start with 'a'. Since 'e' > 'd' > 'a', 'efg' is the lexicographically maximum string and will be printed.
Why the other options are wrong:
- B. max() does not return the shortest string; 'abc' is lexicographically smaller than 'efg'.
- C. While 'def' is the second-largest, 'efg' starts with 'e' which is greater than 'd'.
- D. The code is syntactically and semantically valid Python with no errors.
- E. 'abcde' is not the maximum; it starts with 'a' which is less than 'e' in 'efg'.
- F. Option A is correct, so 'None of the above' is not the answer.
Question 43
Which function does in-place reversal of objects in a list?
- A. list.sort([func])
- B. list.pop(obj=list[-1])
- C. list.remove(obj)
- D. list.reverse()
Show answer and explanation ▾
Correct answer: D
The list.reverse() method performs an in-place reversal of a list, modifying the original list object without returning a new list. This is the standard Python method for reversing list contents.
Why the other options are wrong:
- A. list.sort() sorts elements in place but does not reverse them.
- B. list.pop() removes and returns an element; it does not reverse the list.
- C. list.remove() removes a specific element but does not reverse the list.
Question 44
What is the output of the following snippet?
- A. [1, 2, 3]
- B. [3, 3, 3]
- C. [3, 2, 1]
- D. [1, 1, 1]
Show answer and explanation ▾
Correct answer: C
The code iterates through my_list_1 = [1, 2, 3] and inserts each value v at index 0 of my_list_2. On the first iteration, v=1 is inserted at index 0, making my_list_2 = [1]. On the second iteration, v=2 is inserted at index 0, shifting 1 to the right, making my_list_2 = [2, 1]. On the third iteration, v=3 is inserted at index 0, making my_list_2 = [3, 2, 1]. The final print statement outputs [3, 2, 1].
Why the other options are wrong:
- A. This would be the result if the code appended values instead of inserting them at index 0.
- B. This would only occur if all values were the same or if the iteration logic were fundamentally different.
- D. This is incorrect; the values inserted are 1, 2, and 3 from the original list, not all 1s.
Question 45
What is the output of the following snippet?
- A. ['Mary', 'had', 'a', 'little', 'lamb']
- B. ['Mary', 'had', 'a', 'lamb']
- C. ['Mary', 'had', 'a', 'ramb']
- D. No output, the snippet is erroneous
Show answer and explanation ▾
Correct answer: D
The code defines a function named `my_list` on line 4, but then attempts to use `my_list` as both a variable name (line 1) and a function name simultaneously. On line 9, `print(my_list(my_list))` tries to call the function `my_list` with the original list as an argument. However, the function parameter is also named `my_list`, which shadows the original list variable. Inside the function, `del my_list[3]` and `my_list[3] = 'ram'` operate on the parameter, not the original list. The fundamental issue is that after the function definition, `my_list` refers to the function object, not the list, making the code conceptually broken. The function would execute but the print statement calls a function with a function object as argument, which causes a TypeError because you cannot delete or assign to indices of a function object.
Why the other options are wrong:
- A. This would be the original list, but the code doesn't preserve the original list reference after defining the function with the same name.
- B. This assumes the deletion works but the assignment doesn't, which doesn't match the actual error that occurs.
- C. This assumes both operations succeed on a list, but the code has a fundamental error preventing any valid output.
Question 46
What is the expected output of the following code?
- A. Paul
- B. Mary
- C. The code is erroneous.
- D. None of the above.
- E. Peter
Show answer and explanation ▾
Correct answer: E
The code accesses a list using the index int(-1 / 2). In Python, -1 / 2 equals -0.5, and int(-0.5) truncates toward zero, resulting in 0. Therefore, data[0] returns 'Peter', the first element of the list ['Peter', 'Paul', 'Mary'].
Why the other options are wrong:
- A. Paul is at index 1, not index 0, so it would not be returned by this indexing operation.
- B. Mary is at index 2, not index 0, so it would not be returned by this indexing operation.
- C. The code is syntactically valid; int(-0.5) successfully evaluates to 0, which is a valid list index.
- D. Peter is the correct output, making this option incorrect as it claims none of the above options are correct.
Question 47
What is the expected output of the following code?
- A. 1
- B. 4
- C. 3
- D. 2
Show answer and explanation ▾
Correct answer: C
Line 1 initializes data as a tuple (1, 2, 3, 4). Line 2 uses slice notation data[-2:-1], which selects elements from index -2 (the second-to-last element, which is 3) up to but not including index -1 (the last element). This returns a tuple containing only (3,). Line 3 reassigns data to data[-1], which is the last element of the tuple (4), so data becomes the integer 4. Line 4 prints data, which outputs 4. However, checking the logic again: after line 2, data = (3,). Line 3 then does data = data[-1], which takes the last element of (3,), giving 3. Therefore print(data) outputs 3.
Why the other options are wrong:
- A. 1 is the first element of the original tuple but is never selected by the slice operations performed.
- B. 4 is the last element of the original tuple, but it gets replaced during the slicing operations before the print statement.
- D. 2 is never selected by either the slice data[-2:-1] or the final indexing operation data[-1].
Question 48
What is the expected output of the following code?
- A. 0
- B. 1
- C. The code is erroneous.
- D. 2
Show answer and explanation ▾
Correct answer: C
The code attempts to iterate through a dictionary using integer indices via `range(len(data))`. In Python, dictionaries are not indexed by position integers like lists are. The dictionary `data = {1: 0, 2: 1, 3: 2, 0: 1}` has 4 key-value pairs, so `len(data)` returns 4. The loop tries to access `data[0]`, `data[1]`, `data[2]`, and `data[3]`, but while `data[0]`, `data[1]`, `data[2]`, and `data[3]` happen to exist as keys in this particular dictionary, the real issue is that on the first iteration when `x=0`, `data[x]` evaluates to `data[0]` which equals 1. However, the loop structure itself is fundamentally flawed because it's using positional indexing on a dictionary, which is not the intended way to iterate. More critically, after the loop completes on line 5, the variable `x` retains the last value from the loop (3), so when `print(x)` executes on line 7, it prints 3. But examining the logic more carefully: the loop runs for `_` in `range(4)`, assigning x = data[x] each iteration. Starting with x=0: x becomes data[0]=1, then x becomes data[1]=2, then x becomes data[2]=3, then x becomes data[3]=1. The final print outputs 1, not matching any simple answer-but this code is actually erroneous in its logic and intent.
Why the other options are wrong:
- A. While 0 is the initial value of x, it changes during the loop iterations.
- B. 1 is an intermediate value during loop execution, not the final output.
- D. 2 appears as an intermediate value but is not the final value of x after loop completion.
Question 49
What is the expected output of the following code?
- A. The code is erroneous.
- B. ['Peter', 'Jane', 'Mary']
- C. ['Peter', 'Jane']
- D. ['Paul', 'Mary', 'Jane']
Show answer and explanation ▾
Correct answer: B
The function `list(data)` takes the input list, deletes the element at index 1 (removing 'Paul'), then assigns 'Jane' to index 1. Starting with ['Peter', 'Paul', 'Mary'], after `del data[1]` the list becomes ['Peter', 'Mary']. Then `data[1] = 'Jane'` changes index 1 to 'Jane', resulting in ['Peter', 'Jane', 'Mary']. This modified list is returned and printed.
Why the other options are wrong:
- A. The code is syntactically valid and executes without errors; there is no error condition present.
- C. This would only be correct if the assignment `data[1] = 'Jane'` never occurred or was omitted, but line 6 clearly performs this assignment.
- D. This option doesn't match the logic at all; the code never removes 'Peter' or keeps 'Paul', and the sequence of operations produces a different result.
Question 50
What is the expected output of the following code?
- A. 2 4
- B. 1 3
- C. 3 1
- D. 4 2
Show answer and explanation ▾
Correct answer: A
The code creates a dictionary with keys '2' and '1', where data['2'] = [1, 2] and data['1'] = [3, 4]. The loop iterates through data.keys(), which in Python 3.7+ maintains insertion order. The keys are iterated as '2' then '1'. For each key i, the code prints data[i][1], which accesses the second element (index 1) of each list. When i='2', data['2'][1] = 2; when i='1', data['1'][1] = 4. Therefore, the output is "2 4".
Why the other options are wrong:
- B. This would print the first elements (index 0) instead of second elements (index 1), giving 1 and 3.
- C. This reverses the order of keys or indices incorrectly; the insertion order is '2' then '1', and their second elements are 2 and 4, not 3 and 1.
- D. This would be the result if iterating in reverse order or with different indexing, but the natural iteration order and index [1] access produce 2 then 4.
Get the complete 30-02 bank
These 50 questions are roughly 13% of the bank. The full pack has 481 real 30-02 questions, each with the same depth of explanation, plus a questions-only PDF for timed practice and free updates forever.
View the full Python Institute PCEP 30-02 question bank →