Back to Chapters
Chapter Progress: 0 %0 / 7 Lessons Read
‹›

4. Lists

4.4 Remove items

Highlights & notes

Select lesson text to highlight it, or tap Add note.

    Bookmarks

    Bookmark a lesson to see it here.

      Four ways to remove items:

      • remove(x) removes the first item equal to x.
      • pop() removes the last item and gives it back. pop(i) removes the item at index i.
      • del list[i] deletes by index.
      • clear() empties the list.

      Example

      Python
      files = ["orders.csv", "tmp.csv", "users.csv", "events.csv"]
      files.remove("tmp.csv")
      last = files.pop()
      print(last)
      del files[0]
      print(files)
      files.clear()
      print(files)
      Output
      events.csv
      ['users.csv']
      []
      Must Know:

      remove raises ValueError if the value isn't there, and pop() on an empty list raises IndexError. Check with in or len first.

      Practice in Python

      From queue, remove "spam", then pop the last job into done. Print done, then queue.

      Expected output
      report
      ['load', 'clean']

      Reference solution
      queue = ["load", "spam", "clean", "report"]
      queue.remove("spam")
      done = queue.pop()
      print(done)
      print(queue)

      Question 1 · Easy

      x = [1, 2, 3]; x.pop(). What is x?

      Question 2 · Medium

      x = ["a", "b", "a"]; x.remove("a"). What is x?

      Question 3 · Hard

      x = [10, 20, 30]; y = x.pop(0). What is y?

      Key takeaways

      remove(x) by value, pop() / pop(i) by position and gives the item back, del by index, clear() empties.

      Lesson 17 of 67

      Save your progress

      Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.

      Start free Log in
      PreviousRemove items
      Save your progress free for 1 month. Start free · Log in