Loops, and where your data lives

INPUT · Slides

Getting one by number

01 / 07

When you only want one

for goes over everything in a list. But sometimes you only want to see the second one.

For that you name the number of the one you want. It goes in square brackets after the name of the list.

02 / 07

Counting starts at 0

Here is the first hurdle. The one at the front is number 0, not number 1.

So a list of three is numbered 0, 1, 2. It sits one off from everyday counting, so count on your fingers until it settles.

fruits = ["apple", "orange", "grape"]print(fruits[0])print(fruits[1])print(fruits[2])

Result

apple
orange
grape

03 / 07

Why it starts at 0

It makes more sense if you read the number not as "which one" but as "how far it is from the front".

The front is no distance from the front, so 0. The next is one along, so 1. It is measuring a distance.

And if that does not convince you, never mind. It is partly a thing your fingers learn by use.

04 / 07

You can count from the back

Python has a kindness here. Write a minus and it counts from the back.

[-1] is the very last, [-2] the one before it. You can grab the end without knowing how many there are.

Most other languages have nothing like it. It is one of the Python touches.

fruits = ["apple", "orange", "grape"]print(fruits[-1])print(fruits[-2])

Result

grape
orange

05 / 07

Ask for a number that is not there and it complains

What happens if you ask for [3] when only three things are in? You get an error and the program stops.

It means "that number is outside the range". The last number is one less than the count, so writing one too many is the classic stumble.

fruits = ["apple", "orange", "grape"]print(fruits[3])

Result

IndexError: list index out of range

06 / 07

What comes out is an ordinary value

Once it is out, you can forget it came from a list. It is just the value, sitting there.

Put it in a variable, do sums with it, compare it with if — everything you have learned so far applies as it stands.

scores = [80, 95, 60]total = scores[0] + scores[1]print(total)

Result

175

07 / 07

In short

  • fruits[0] … the front. Counting starts at 0
  • fruits[-1] … the very last
  • ask for a number that is not there and you get an IndexError

Next you learn to do more than take things out — to swap, add and remove what is inside.