English

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) - Computer Science (Python)

Advertisements
Advertisements

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")
Code Writing
Advertisements

Solution

The loop runs on given[1:-1].
  • String: G o l d - 2 4 M e d a l s
  • Sliced portion: old-24Medal (removes the first 'G' and last 's').

The logic is: If Uppercase → reverse(); If not in list → append(); If already in list → pop().

Character (ch) Condition new list 
o Not in new ['o']
I Not in new ['o', 'l']
d Not in new ['o', 'l', 'd']
- Not in new ['o', 'l', 'd', '-']
2 Not in new ['o', 'l', 'd', '-', '2']
4 Not in new ['o', 'l', 'd', '-', '2', '4']
M Uppercase ['4', '2', '-', 'd', 'l', 'o'] (Reversed)
e Not in new ['4', '2', '-', 'd', 'l', 'o', 'e']
d Already in ['4', '2', '-', 'd', 'l', 'o'] (pop() removes 'e')
a Not in new ['4', '2', '-', 'd', 'l', 'o', 'a']
I Already in ['4', '2', '-', 'd', 'l', 'o'] (pop() removes 'a')

The final print(new) The command displays the list:

['4', '2', '-', 'd', 'l', 'o']

shaalaa.com
  Is there an error in this question or solution?
2025-2026 (March) Set 4

APPEARS IN

Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×