Find the output of the code:
answer=[ ]
output=' '
answer.append('F')
answer.append('I')
answer.append('L')
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=ch
print(“Result=”,output)
Find the output of the code:
answer=[ ]
output=' '
answer.append('F')
answer.append('I')
answer.append('L')
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=output+ch
ch=answer.pop()
output=ch
print(“Result=”,output)
Solution
The list works as a stack, so pop() removes the last item each time, giving 'L', then 'I', then 'F'.
The first two pops build the string up to ' LI'. The last line is output=ch, not output=output+ch, so it replaces the whole string with 'F'. The program therefore prints Result= followed by F.
Option 2: this would be the result only if the last line were output=output+ch. It is an assignment, so the earlier characters are discarded.
Option 1: pop() removes from the end (last in, first out), not from the front, so the order is never F, I, L.
Option 4: 'L' is the first value popped, but it is overwritten later.
Related questions:
2025: 22 May Shift 1
2026: 23 May Shift 1
2026: 24 May Shift 1