Consider the following assignment for a List L. L = [10, 20, 30, 40, 50, 60]…
2023
Consider the following assignment for a List L. L = [10, 20, 30, 40, 50, 60] Which print statement option will display the content in the following way? [60, 10, 20, 30, 40, 50]
- A.
print(L[-1] + L[1:])
- B.
print([L[-1]] + L[:len(L)-1])
- C.
print(L[len(L)-1] + L[1:len(L)])
- D.
print(L[-1], L[1:])
Attempted by 1881 students.
Show answer & explanation
Correct answer: B
Correct approach: Use [L[-1]] + L[:len(L)-1] which makes the last element a single-item list and concatenates it with the list of all elements except the last. For L = [10, 20, 30, 40, 50, 60] this evaluates to [60, 10, 20, 30, 40, 50].
Why other options are incorrect:
print(L[-1] + L[1:]) - L[-1] is an integer and L[1:] is a list, so this raises a TypeError (cannot add int and list). Use [L[-1]] to make it a list before concatenation.
print(L[len(L)-1] + L[1:len(L)]) - Same TypeError problem: the first part is an integer. Additionally, L[1:len(L)] starts at the second element, so the logic would not produce the intended rotation even if types were corrected.
print(L[-1], L[1:]) - This prints two separate objects (e.g., 60 [20, 30, 40, 50, 60]) rather than a single concatenated list, and the slice used does not include the first element 10.
Example output: [60, 10, 20, 30, 40, 50]
Note: L[:len(L)-1] can be written more concisely as L[:-1].