Skip to content

Sep 25: Searching, Modifying Lists

Learning Objectives

After today's class, you should be able to:

  • Summarize which operators can be applied to a list.
  • Summarize built-in functions and methods for a list.
  • Write a program that manipulates and searches a list.

Reminders

  • Due tomorrow
  • Quiz 2b on Wednesday
    • Based on HW 3 and HW 4
    • Lists/containers not allowed

List Operations

  • Useful documentation
  • Some methods to learn:
    • append(v) – adds value v to the end
    • pop() – removes value from the end
    • pop(i) – removes value at index i
    • insert(i, v) – insert v at index i
    • remove(v) – removes first element v
    • count(v)– number of value v in list
    • index(v) – index of first element v
  • You don't need to memorize!
    • Use the help() function in the Shell
    • Use the "Object inspector" in Thonny

Little Free Library

photo of little free library

A Little Free Library is a community library that lets people borrow and contribute books. The library survives on the "take a book, leave a book" principle. If someone takes a book (like "Project Hail Mary"), they have to add another book to the library (like "The Martian"). It’s a great way for people to share books!

In this lab, you will create a library.py program to simulate a Little Free Library. At the top of your program, after the docstring, assign a variable named books that contains the list of books in the library:

books = ["Project Hail Mary", "The Hobbit", "Sherlock Holmes", "The Hobbit", "Dune"]

(Note: If we were to submit this lab, which we won't, then Gradescope would replace the contents of this variable with other books.)

The first thing the program should do is display a title, the number of books in the library, and all the books, followed by a blank line:

= Little Free Library =
Count: 5 book(s)
['Project Hail Mary', 'The Hobbit', 'Sherlock Holmes', 'The Hobbit', 'Dune']

The program should then ask the user which book they would like and tell the user how many copies of that book are available:

Enter the title of a book to find: The Hobbit
We have 2 copies of "The Hobbit" available.

Then, the program should ask the user for the index of a book to take, print the name of the book, then remove it from the list and print the updated list, followed by a blank line:

Enter the index of a book to take: 1
You took "The Hobbit".
['Project Hail Mary', 'Sherlock Holmes', 'The Hobbit', 'Dune']

Finally, ask the user for the name of a book they would like to leave, and put the book at the end of the list. Print out the full list of books again to show what the list looks like now.

What book would you like to leave? The Martian
['Project Hail Mary', 'Sherlock Holmes', 'The Hobbit', 'Dune', 'The Martian']