Accessing Elements of Lists

Accessing Elements of Lists

Lists are pretty useful, but only if you can get at the things inside them. You can already go through the elements of a list in order, but what if you want, say, the fifth element? You need to know how to access the elements of a list. Here’s how you would access the first element of a list:

animals = ['bear', 'tiger', 'penguin', 'zebra']
bear = animals[0]

You take a list of animals, and then you get the first (1st) one using 0?! How does that work? Because of the way math works, Python start its lists at 0 rather than 1. It seems weird, but there’s many advantages to this, even though it is mostly arbitrary.

The best way to explain why is by showing you the difference between how you use numbers and how programmers use numbers.

Imagine you are watching the four animals in our list above ([‘bear’, ‘tiger’, ‘penguin’, ‘zebra’]) run in a race. They win in the order we have them in this list. The race was really exciting because the animals didn’t eat each other and somehow managed to run a race. Your friend, however, shows up late and wants to know who won. Does your friend say, “Hey, who came in zeroth?” No, he says, “Hey, who came in first?”

This is because the order of the animals is important. You can’t have the second animal without the first (1st) animal, and you can’t have the third without the second. It’s also impossible to have a “zeroth” animal since zero means nothing. How can you have a nothing win a race? It just doesn’t make sense. We call these kinds of numbers “ordinal” numbers, because they indicate an ordering of things.

 animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
  1. The animal at 1.
  2. The third animal.
  3. The first animal.
  4. The animal at 3.
  5. The fifth animal.
  6. The animal at 2.
  7. The sixth animal.
  8. The animal at 4

For each of these, write out a full sentence of the form: “The first animal is at 0 and is a bear.” Then say it backward, “The animal at 0 is the first animal and is a bear.” Use your Python to check your answers.

Study Drills

  1. Read about ordinal and cardinal numbers online.
  2. With what you know of the difference between these types of numbers, can you explain why the year 2010 in “January 1, 2010,” really is 2010 and not 2009? (Hint: you can’t pick years at random.)
  3. Write some more lists and work out similar indexes until you can translate them.
  4. Use Python to check your answers to this as well.