Find the output of the following Python code: def StringTwist(STR, L): STR =…
2026
Find the output of the following Python code:
def StringTwist(STR, L):
STR = STR.title()
L[0] *= 2
L[1] += L[0]
L.append(STR)
print("Twist String:", STR) # Output 2A
print("List:", L) # Output 2B
TEXT = "peace park"
VAL = [5, 10]
StringTwist(TEXT, VAL)
VAL[0] *= 5
print("String:", TEXT) # Output 2C
print("List:", VAL) # Output 2DAttempted by 32 students.
Show answer & explanation
Concept
In Python, function parameters are local names bound to the objects supplied by the caller.
Rebinding a parameter to a new immutable string does not change the caller’s name, while mutating a shared list changes that same list object. Augmented assignment to a list element therefore remains visible after the function returns.
Application
Initially,
TEXTrefers to"peace park"andVALrefers to[5, 10].STR = STR.title()creates"Peace Park"and rebinds only the local nameSTR;TEXTstill refers to"peace park".L[0] *= 2changes the shared list from[5, 10]to[10, 10].L[1] += L[0]uses the updated first element, so the list becomes[10, 20].L.append(STR)appends the locally titled string, producing[10, 20, "Peace Park"]. The two prints inside the function use these local/current values.After the call,
VALstill refers to the mutated list.VAL[0] *= 5changes its first element from10to50, whileTEXTremains"peace park".
For a string of length n, title conversion dominates the trace at O(n); the fixed list updates and this append are constant-time operations apart from append’s standard amortized behavior.
Cross-check
The trace predicts that the list mutations must remain visible through VAL, whereas the local string rebinding must not change TEXT. Running the code under standard Python 3 semantics produces exactly that pattern:
Twist String: Peace Park
List: [10, 20, 'Peace Park']
String: peace park
List: [50, 20, 'Peace Park']Result
Therefore, the four output lines are the lines shown above, in the same order.