count(), as the name implies, counts the occurrences of a given argument in a list or a string. It is used in the two ways shown below.
On the left,since “educative” has two instances of the letter ‘e’,
count() returns 2. On the right, since “apples” occurs three times in the list,
count() returns 3.
elephant occurs twice in
mylist, the function returns
mylist = ["elephant", "hippo", "panda", "elephant", "bear"] print(mylist.count("elephant"))
Here, the string in
substr is searched in the entire string
sea occurs twice, hence why the function returns
A slight modification to count from a string involves passing a starting and ending index. The string will be searched for the value within this range. The syntax for doing this is:
string.count(substr, start, end)
mystr = "sally sells sea shells on the sea shore" substr = "sea" print(mystr.count(substr))
substr is searched in
mystr from position 0 to 8, only. Feel free to change these values, note change in result.
mystr = "educative is awesome, right?" substr = 'a' print(mystr.count(substr, 0, 8))