List Methods · Exercises
Beginner

List Methods Exercises

4 exercises that build on the Python List Methods lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: List methods are built-in functions, called with a dot, that add, remove, find and copy items, and most of them change the list in place and return None. By the end you can choose between append, insert and extend, between remove, pop and del, and tell which methods change the list and which return a value. You will practise: Build the guest list; Predict the stack; Fix add_scores; Undo and redo.

0 / 4 completed

List Methods practice exercises

1. Build the guest list

Write code Easy

The list guests holds three names and late_arrivals holds two more. Using list methods on guests (do not retype the list):

  1. add "Dev" at the end,
  2. insert "Zoe" so she is the first guest,
  3. add every name from late_arrivals,
  4. remove "Ben".

Then print guests. It should end up as ['Zoe', 'Asha', 'Chen', 'Dev', 'Eli', 'Fay'].

Your code
guests = ["Asha", "Ben", "Chen"]
late_arrivals = ["Eli", "Fay"]

# your code here

2. Predict the stack

Predict the output Medium

Read the code and type exactly what it will print, line by line. Track the list after every call, and remember what each method returns.

Read this code
stack = [1, 2, 3]
stack.append([4, 5])
stack.extend([6, 7])
print(stack)

top = stack.pop()
print(top, len(stack))

result = stack.remove(1)
print(result)
print(stack + [0])
print(stack)

3. Fix add_scores

Fix the bug Medium

add_scores(scores, new_scores) should add every number from new_scores to the end of scores, change that list in place and return it. For the call below it should print [70, 85, 90, 95], but it prints [70, 85, [90, 95]]. Fix the bug.

Your code
def add_scores(scores, new_scores):
    scores.append(new_scores)
    return scores

grades = [70, 85]
print(add_scores(grades, [90, 95]))

4. Undo and redo

Write code Hard

Write a function edit(actions) that replays a list of actions on a document and returns the words left in it (a list).

  • Any action other than "undo" and "redo" is a word: add it to the end of the document. Typing a new word also wipes everything that could still be redone.
  • "undo" removes the last word from the document and remembers it, so it can be redone. If the document is empty, do nothing.
  • "redo" puts back the word that was undone most recently. If there is nothing to redo, do nothing.

For example, edit(["a", "b", "c", "undo", "undo", "redo"]) returns ["a", "b"]. Do not change the actions list you receive.

Your code
def edit(actions):
    document = []
    redo = []
    for action in actions:
        pass  # your code here
    return document

print(edit(["Hello", "big", "world", "undo", "undo", "redo"]))

Next lessonPython Slicing

More Python List Methods examples · All Python exercises