The first method we’ll talk about is called
count
. You can call the count() method on any string, list, or tuple, by using
variable_name.count(<itemtocount>)
. The count() method requires that you provide one argument, which is what you would like to count. The method then returns the number of times that the argument occured in the string/list/tuple the method was used on. There are some differences between count for strings and count for lists. When you use count on a string, the argument can only be a string. You can’t count how many times the integer 2 appears in a string, though you can count how many times the string “2” appears in a string. For lists and tuples, the argument can be any type: a string, an integer, a floating point number, a boolean value, etc.
The activecode window above demonstrates the use of count on a string. Just like with the turtle module when we had to specify which turtle was changing color or moving, we have to specify which string we are using count on.
When you run the activecode window above, you’ll see how count with a list works. Notice how “4” has a count of zero but 4 has a count of three. This is because the list
z
only contains the integer 4. There are no strings in this list that are “4”. Additionally, when we check the count of “a”, we see that the program returns zero. Though some of the words in the list
contain the letter “a”, the program is looking for items in the list that are
just the string “a”.