3 Going on a picnic: Working with lists

 

Writing code makes me hungry! Let’s write a program to list some tasty foods we’d like to eat.

So far we’ve worked with single variables, like a name to say “hello” to or a nautical-themed object to point out. In this program, we want to keep track of one or more foods that we will store in a list, a variable that can hold any number of items. We use lists all the time in real life. Maybe it’s your top-five favorite songs, your birthday wish list, or a bucket list of the best types of buckets.

In this chapter, we’re going on a picnic, and we want to print a list of items to bring along. You will learn to

  • Write a program that accepts multiple positional arguments
  • Use if, elif, and else to handle conditional branching with three or more options
  • Find and alter items in a list
  • Sort and reverse lists
  • Format a list into a new string

The items for the list will be passed as positional arguments. When there is only one item, you’ll print that:

$ ./picnic.py salad
You are bringing salad.

What? Who just brings salad on a picnic? When there are two items, you’ll print “and” between them:

$ ./picnic.py salad chips
You are bringing salad and chips.

3.1 Starting the program

3.2 Writing picnic.py

3.3 Introducing lists

3.3.1 Adding one element to a list

3.3.2 Adding many elements to a list

3.3.3 Indexing lists

3.3.4 Slicing lists

3.3.5 Finding elements in a list

3.3.6 Removing elements from a list

3.3.7 Sorting and reversing a list