The subscript operator

The subscript operator is defined as square brackets []. It is used to access the elements of string, list tuple, and so on. Let's discuss the syntax with an example:

<given string>[<index>]

The given string is the string you want to examine and the index is the position of the character you want to obtain. Let's discuss this with an example:

>>> name = "The Avengers"
>>> name[0]
'T'
>>> len(name)
12
>>> name[11]
's'
>>>
>>> name[12]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
name[12]
IndexError: string index out of range
>>>

The "The Avengers" string is 12 characters long, which means it ranges from 0 to 11 index. The name[0] represents the character 'T'.  If you give the 12th index value, then the Python interpreter generates an error out of range.

Let's see what is negative indexing:

>>> name[-1]
's'
>>> name[-12]
'T'
>>>

The -1 index represents the last character and -12 represents the first character.

In the computer world, the computer counts the index from 0 itself.

The following diagram will clear all your doubts:

Positive and negative indexing
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.174