Start learning free

LESSON 118 OF 673 · LISTS - CHALLENGES

Undo the Last Add in Python: append and pop

Practice Read the full explanation

You keep a shopping list, a list of strings items. Add the word first to the end of the list, then add the word second to the end, then undo the last add by removing the last item. Return the list.

The undo always removes the item at the end of the list, even when the same word also appears earlier in the list.

 

Example 1:

Input: items = ["milk", "eggs"], first = "bread", second = "jam"
Output: ["milk", "eggs", "bread"]
Explanation: After the two adds the list is ["milk", "eggs", "bread", "jam"]. The undo removes "jam", the last item.

Example 2:

Input: items = [], first = "apples", second = "pears"
Output: ["apples"]
Explanation: The list starts empty. "apples" and "pears" are added, then "pears" is removed.

Example 3:

Input: items = ["water"], first = "juice", second = "water"
Output: ["water", "juice"]
Explanation: The list becomes ["water", "juice", "water"]. The undo removes the last item, the "water" just added, not the first one.

 

Constraints:

  • items has between 0 and 10 words: it may be empty.
  • first, second and every word in items are single words of lowercase English letters.
  • The same word may appear more than once.
STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · LISTS - CHALLENGES

    Undo The Last Add in Python, explained

    Problem overview

    The function undoLastAdd receives a list of strings, items, and two words, first and second. It adds first to the end of the list, then adds second to the end, then undoes the last add by removing the last item. It returns the list.

    With items = ["milk", "eggs"], first = "bread" and second = "jam", the list grows to ["milk", "eggs", "bread", "jam"], the undo removes "jam", and the result is ["milk", "eggs", "bread"]. With an empty list, "apples" and "pears", the result is ["apples"].

    Approach

    This lesson is about two list methods that work at the end of a list. append puts one item after all the others. pop with no argument removes the last item and gives it back. Together they behave like a stack: the item added last is the first one removed.

    That is why the undo is safe when a word repeats. pop() goes by position, not by value, so it never searches for a word. With items = ["water"], first = "juice" and second = "water", the list becomes ["water", "juice", "water"] and pop() removes the last "water", the one just added. The function returns ["water", "juice"].

    Lists can also remove from the front or the middle: pop(0) removes the first item, and del items[-1] removes the last one like pop() does, without giving the item back. For an undo, plain pop() says what it means and is the usual choice. It also runs in constant time, since nothing has to shift.

    Step by step

    1. Append first. It lands after whatever is already in the list, and on an empty list it becomes the only item.
    2. Append second. It is now the last item.
    3. Call pop(). This removes the last item, which is second, and leaves first at the end.
    4. Return items.

    The solution in Python

    class Solution:
        def undoLastAdd(self, items: List[str], first: str, second: str) -> List[str]:
            items.append(first)
            items.append(second)
            items.pop()
            return items
    

    Some details worth knowing:

    • The list is changed in place. append and pop change the very list the caller passed in, and the function returns that same list. After l = ["a"] and a call with "b" and "c", both l and the returned list are ['a', 'b'], and the two names refer to one object.
    • append returns None. Writing items = items.append(first) would replace the list with None. Call the method on its own line, as above.
    • pop() returns the removed item. Here the value is not needed, so it is simply discarded.
    • The type names. List[str] only documents the types. It doesn't check anything when the code runs.

    Edge cases and common mistakes

    • Empty list. It works with no special case: after the two appends the list has two items, so pop() has something to remove. Calling pop() on a list that is empty raises IndexError.
    • Repeated words. Removing by value, as in items.remove(second), removes the first matching item. For ["water"] it would take out the original "water" and leave ["juice", "water"], which is wrong.
    • Same word twice. If first and second are equal, as in ["x", "y"] with "z" and "z", one "z" stays: the result is ['x', 'y', 'z'].
    • Wrong order. Appending second before first would leave second in the list instead.

    Testing

    • ["milk", "eggs"], "bread", "jam" gives ['milk', 'eggs', 'bread'].
    • [], "apples", "pears" gives ['apples'].
    • ["water"], "juice", "water" gives ['water', 'juice'].
    • ["x", "y"], "z", "z" gives ['x', 'y', 'z'].
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free