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 2D

Attempted 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

  1. Initially, TEXT refers to "peace park" and VAL refers to [5, 10].

  2. STR = STR.title() creates "Peace Park" and rebinds only the local name STR; TEXT still refers to "peace park".

  3. L[0] *= 2 changes the shared list from [5, 10] to [10, 10].

  4. L[1] += L[0] uses the updated first element, so the list becomes [10, 20].

  5. L.append(STR) appends the locally titled string, producing [10, 20, "Peace Park"]. The two prints inside the function use these local/current values.

  6. After the call, VAL still refers to the mutated list. VAL[0] *= 5 changes its first element from 10 to 50, while TEXT remains "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.

Explore the full course: Hpsc Pgt Computer Science

Loading lesson…