Next / Previous / Contents / TCC Help System / NM Tech homepage

4.4. Sequence methods

To find the position of a value V in a sequence S, use this method:

S.index(V)

This method returns the position of the first element of S that equals V. If no elements of S are equal, Python raises a ValueError exception.

>>> menu1
['beans', 'kale', 'tofu', 'trifle', 'sardines']
>>> menu1.index("kale")
1
>>> menu1.index("spam")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: list.index(x): x not in list

The method S.count(V) method returns the number of elements of S that are equal to V.

>>> menu1[2:2] = ['spam'] * 3
>>> menu1
['beans', 'kale', 'spam', 'spam', 'spam', 'tofu', 'trifle', 'sardines']
>>> menu1.count('gravy')
0
>>> menu1.count('spam')
3
>>> "abracadabra".count("a")
5
>>> "abracadabra".count("ab")
2
>>> (1, 6, 55, 6, 55, 55, 8).count(55)
3