Indexes: Examples

It's pretty easy to figure out indexes when we can count by hand. Now let's try doing it programmatically (that is, using Python).

Try the first example. At your prompt, type the word print , then inside parentheses, the word "Hello" in quotes, and finally these square brackets with the number zero inside. Then hit Enter.

>>> print("Hello"[0])

H

Since we're asking for the character in this string with an index of zero, Python returns the letter 'H'.

Now let's try the second example, asking Python for the character with an index of 4.

>>> print("Hello"[4])

Did you get the letter 'o'? Let's see why.

H e l l o

0 1 2 3 4

If we start at the beginning of the string, the letter 'H' is at index, or position, zero. Then index 1 is the letter 'e', indexes 2 and 3 are 'l'. And index 4 is the letter 'o'.

Okay, let's try a longer example:

>>> print("Hey, Bob!"[4])

Did Python return anything? Are you sure? Count by hand and see what character is at index 4.

Remember to start with zero - that's the letter 'H'. Index 1 is the letter 'e', 2 is the letter 'y', 3 is the comma, and 4 is the space. Could that be what Python returned?

Okay, one last example. We already know that we can enter an index number inside the square brackets to find its matching character in the string.

But we can also do math inside those square brackets.

>>> print("Hey, Bob!"[6-1])

Here we're subtracting 1 from 6. That comes out to 5. What is the character at index 5 in this string?

Answers:

>>> print("Hello"[4])

o

>>> print("Hey, Bob!"[4])

>>> print("Hey, Bob!"[6-1])

B