Question:hard

A stack named FruitStack, implemented using list, contains records of some fruits. Each record is represented as a dictionary with keys 'Name', 'Origin', 'Price', and 'Expiry'. A sample record is given here:

{'Name':'Apple','Origin':'France','Price':120,'Expiry':'12-08-2025'}

Write the following user-defined functions in Python to perform the specified operations on FruitStack:

(i) push_fruit(FruitStack, Fruit): This function takes the stack FruitStack and a new record Fruit as arguments and pushes the record stored in Fruit onto FruitStack if the Price is less than 100.

(ii) pop_fruit(FruitStack): This function pops the topmost record from the stack and returns it. If the stack is already empty, the function should display “UNDERFLOW”.

(iii) display(FruitStack): This function displays all the elements of the stack starting from the topmost element. If the stack is empty, the function should display 'EMPTY STACK'.

Show Hint

Use append() for push when Price is below 100, pop() with an emptiness check, and a loop from the last index to 0 for display.
Updated On: Oct 20, 2026
Show Solution

Solution and Explanation

Step 1: Break the task into three small jobs:
We need one function to add a record under a condition, one to remove the top record safely and one to print the stack from the top.
In a list-based stack, the top is the last element. All three jobs follow from this fact.

Step 2: Condition before push:
def push_fruit(FruitStack, Fruit):
    if Fruit['Price'] < 100:
        FruitStack.append(Fruit)

If the price is 100 or more, nothing happens and the stack stays as it was.

Step 3: Safe pop:
Calling pop() on an empty list raises an error. So we test for emptiness first, and show UNDERFLOW instead of crashing.
def pop_fruit(FruitStack):
    if FruitStack == []:
        print('UNDERFLOW')
    else:
        return FruitStack.pop()


Step 4: Display from the top:
The reversed() function walks a list from the last element to the first. This gives the order top to bottom.
def display(FruitStack):
    if FruitStack == []:
        print('EMPTY STACK')
    else:
        for rec in reversed(FruitStack):
            print(rec)


Step 5: Check the behaviour:
With records of price 120, 90 and 60, only the last two get in. display() shows the 60 record first, then the 90 record. A pop removes the 60 record. An empty stack gives the messages EMPTY STACK and UNDERFLOW. I confirmed this by running the code.

Final Answer:
push_fruit(), pop_fruit() and display() as written above perform the three required stack operations.
Was this answer helpful?
0