Question:

Write the output of the following code:

def Exam2026(given) :
    new=[]
    for ch in given[1:-1]:
        if ch.isupper():
            new.reverse()
        elif ch not in new:
            new.append(ch)
        elif ch in new:
            new.pop()
    print(new)
Exam2026("Gold-24Medals")

Show Hint

The loop runs on 'old-24Medal'. An uppercase letter reverses the list, and a repeated character pops the last item.
Updated On: Oct 20, 2026
Show Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Find the string that the loop sees:
The call is Exam2026('Gold-24Medals'). The slice given[1:-1] drops the first and the last character.
So the loop runs over 'old-24Medal', which is the characters o, l, d, -, 2, 4, M, e, d, a, l.
new starts as an empty list.

Step 2: Know the three branches:
If ch is uppercase, the list new is reversed.
Else if ch is not in new, it is appended.
Else if ch is already in new, pop() removes the LAST element of new, not the matching one.

Step 3: Trace the loop:
'o' is not in new, so new = ['o'].
'l' is not in new, so new = ['o', 'l'].
'd' is not in new, so new = ['o', 'l', 'd'].
'-' is appended, so new = ['o', 'l', 'd', '-'].
'2' is appended, then '4' is appended. new = ['o', 'l', 'd', '-', '2', '4'].
'M' is uppercase, so new is reversed to ['4', '2', '-', 'd', 'l', 'o'].
'e' is not in new, so it is appended: ['4', '2', '-', 'd', 'l', 'o', 'e'].
'd' is already in new, so pop() removes the last item 'e': ['4', '2', '-', 'd', 'l', 'o'].
'a' is not in new, so it is appended: ['4', '2', '-', 'd', 'l', 'o', 'a'].
'l' is already in new, so pop() removes the last item 'a': ['4', '2', '-', 'd', 'l', 'o'].

Step 4: Print:
print(new) shows the list with quotes and commas. I ran the code and got the same result.

Final Answer:
['4', '2', '-', 'd', 'l', 'o']
Was this answer helpful?
0
0