indexes in programming

have you ever wonder why indexes always start at  0 but not at 1 ?

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

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 and other progamming languages starts its lists at 0 rather than 1.

The best way to explain why this is happening 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 (['bear', 'tiger', 'penguin', 'zebra']) run in a race. They cross the finish line 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 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.

Programmers, however, can’t think this way because they can pick any element out of a list at any point. To programmers, the list of animals is more like a deck of cards. If they want the tiger, they grab it. If they want the zebra, they can take it too. This need to pull elements out of lists at random means that they need a way to indicate elements consistently by an address, or an “index,” and the best way to do that is to start the indices at 0. Trust me on this: the math is way easier for these kinds of accesses. This kind of number is a “cardinal” number and means you can pick at random, so there needs to be a 0 element.

Remember: ordinal == ordered, 1st; cardinal == cards at random, 0.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s