What is the index operator in python?

Index operator

The index operator (Python uses square brackets to enclose the index) selects a single character from a string.

  • In strings, the characters are accessed by their position or index.

  • In lists and tuples, items are accessed by their position or index.

  • Characters are indexed left to right from position ‘0’ to position ‘13’. Positions are also named from right to left using negative numbers, where -1 is the rightmost index and so on.

Example

List = [10,20,'apple',30,'mango',40]

tuple = ['hello','pi','value','is',3.14]

Code

a="hello students"
b=['hello','pi','value','is',3.14]
c=('hello','pi','value','is',3.14)
l=a[2]
print(l)
lastcher=a[-1]
print(lastcher)
print(b[2])
print(b[3-6])
print(b[-2])
print(c[0])
print(c[-1])
print(c[2-4])
print(b[7-8])

count()

The count method returns the number of times the argument occurred in the string/list upon which the method was used.

  • We cannot count how many times integer 2 occurred, but we can count how many times string ‘2’ occurred.

  • The count method works for lists too.

Code

a="I have had an apple on my desk before!"
print(a.count("e"))
print(a.count("ha"))
z=['atoms',4,'neutron',6,'proton',4,'electron',4,'electron','atoms']
print(z.count("4"))
print(z.count(4))
print(z.count("a"))
print(z.count("electron"))

Free Resources