Python Programming 2 / Chapter 1: Lists / Introduction

Welcome to Python Programming 2!

In the first Python course, we learned how to build Python programs using various kinds of Python statements. In this course, we are going to study Python collections. Applications (or programs) use collections to store and operate on large amounts of data.

For example, suppose that you are building an online library application, and you want to write a function that searches the library catalog. The function input is the search term, and the output is True if the catalog contains the book whose title matches the search term, and False otherwise.

Unfortunately, you can't write this function just yet. To see why, let's try solving a simpler problem. Suppose that the library has exactly 3 books. Then the function header might be:

def search(title_1, title_2, title_3, term):

title_1, title_2, and title_3 are the titles of the 3 books, and term is the customer's text input.

Here is the function body:

if term == title_1:
    return True
elif term == title_2:
    return True
elif term == title_3:
    return True
else:
    return False

If a new book is added to the library, we need to add a new parameter to the function header and a new elif block to the function body. In general:

  • The number of parameters = number of books + 1.
  • The number of if, elif, and else statements = number of books + 1.

If the library has a large collection of books, then the function header and body would also be very large. In addition, whenever books are added to or removed from the library, we need to change both the function header and body and restart the application. Most libraries are both large and dynamic, so our solution won't work.

Thankfully, Python provides collections to address both of these issues. Using collections, we can store many titles inside a single variable. To search Python collections, we can use either while or for loops.

Here is a preview:

def search(titles, term):
    for title in titles:
        if title == term:
            return True
    return False

Course Contents

Python provides many types of collections, including lists, dictionaries, and sets.

In this course, we will study 3 of them:

  1. Lists - the simplest, but most useful, data structure.
  2. Dictionaries - key-value pairs, or maps.
  3. Objects - groups of related data.

We will also study the for loop, which is a convenient way to perform operations on a collection of elements.

Next Lesson

Comments

Please log in to add comments