educative.io

Educative

Why is "e" printed instead of "n"?

batman = "Bruce Wayne"

first = batman[0]  # Accessing the first character
print(first)

space = batman[5]  # Accessing the empty space in the string
print(space)

**last = batman[len(batman) - 1]**

** print(last)**
# The following will produce an error since the index is out of bounds
# err = batman[len(batman)]

In the bolded code, why is “e” printed instead of “n” as the output?

I read the [len(batman) - 1] to simplify to [11 - 1] as the length of (batman) is 11 characters. So, shouldn’t print(last) where last = batman[10] end up at the “n” rather than the “e”? As in, the blank space is included in the character count, correct?

@ratnesh

e is printed instead of v because the array is starting with index 0. When we do [len(batman) - 1], it is pointing to the last value that is e, thus e is printing.

Hi Shaheryaar,

The link is here: lesson

Thanks for the explanation. To clarify though, len(batman) results in 11, correct? Then wouldn’t 11 - 1 result in 10, and point to the 10th character, which would be “n” and not “e”?

To get the second last element we have to subtract 2. This is the same case when we run a loop with length - 1 and we traverse the whole array. Since there’s a space between Bruce and Wayne while iteration that space is discarded in result e is printed.

1 Like