6.8. Count and Index

As you create more complex programs, you will find that some tasks are commonly done. Python has some built-in functions and methods to help you with these tasks. This page will cover two helpful methods for both strings and lists: count and index.

You’ve learned about methods before when drawing with the turtle module. There, you used .forward(50) and .color("purple") to complete actions. We refer to forward and color as methods of the turtle class. Objects like strings and lists also have methods that we can use.

6.8.1. Count

The first method we’ll talk about is called count. It 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 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, the argument is not restricted to just strings.

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 never any strings 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 letter “a”.

6.8.2. Index

The other method that can be helpful for both strings and lists is the index method. The index method requires one argument, and, like the count method, it takes only strings when index is used on strings, and any type when it is used on lists. For both strings and lists, index returns the leftmost index where the argument is found. If it is unable to find the argument in the string or list, then an error will occur.

All of the above examples work, but were you surprised by any of the return values? Remember that index will return the left most index of the argument. Even though “Metatarsal” occurs many times in bio, the method will only return the location of one of them.

Here’s another example.

In the activecode window above, we’re trying to see where “autumn” is in the list seasons. However, there is no string called autumn (though there is string called “fall” which is likely what the program is looking for). Remember that an error occurs if the argument is not in the string or list.

Check your understanding

You have attempted of activities on this page