Removing Elements

Removing Elements

Two methods remove elements from a list.

remove deletes the first element equal to a value:

tasks = ["email", "report", "email", "review"]
tasks.remove("email")
print(tasks)

Output:

['report', 'email', 'review']

Only the first "email" went. Removing a value that is not in the list raises ValueError.

pop deletes by index and returns the removed element. Without an argument it takes the last one:

tasks = ["report", "email", "review"]
finished = tasks.pop()
print(finished)
print(tasks)

Output:

review
['report', 'email']

Use remove when you know the value, pop when you know the position or want the element back.

Exercise

The starter code creates tasks with four entries.

  1. Remove "meeting" by value.
  2. Pop the last element into a variable named done.
  3. Print done, then print tasks. The final list is ['email', 'report'].

Run your code to see the output, then press Submit.

Tests

import unittest


class TestRemovingElements(unittest.TestCase):
    def test_done_is_review(self):
        self.assertEqual(done, "review")

    def test_tasks_has_the_two_remaining_entries(self):
        self.assertEqual(tasks, ["email", "report"])
tasks = ["email", "report", "meeting", "review"]

tasks.remove("meeting")
done = tasks.pop()

print(done)
print(tasks)
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.