Question:hard

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

Solution and Explanation

Step 1: Cut the string first:
given[1:-1] of 'Gold-24Medals' keeps everything except the first letter G and the last letter s. The result is 'old-24Medal', 11 characters long.

Step 2: Notice the first part of the string:
The first six characters o, l, d, -, 2, 4 are all different and none is uppercase. So each one is appended in turn, and new becomes ['o', 'l', 'd', '-', '2', '4'].

Step 3: Handle the uppercase letter:
The next character is 'M'. It is uppercase, so the first branch runs and new.reverse() turns the list into ['4', '2', '-', 'd', 'l', 'o']. 'M' itself is not added.

Step 4: Handle the last three letters e, d, a, l:
'e' is new to the list, so it goes to the end. The list is now ['4', '2', '-', 'd', 'l', 'o', 'e'].
'd' is already there, so the third branch runs. pop() always removes the last item. That item is 'e', so 'e' leaves and 'd' stays.
'a' is new, so it is added at the end.
'l' is already there, so pop() removes the last item, which is 'a'.
The list returns to ['4', '2', '-', 'd', 'l', 'o'].

Step 5: Print the list:
print(new) writes the list in square brackets with quotes around each character. The code gave this exact output when I ran it.

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