14: Methods

So far we have a seen a couple of data structures in Python: strings and lists. They each support several methods, which are variants of functions.

For example, one method of lists is the reverse() method. As the name suggests, it reverses the list (for example the first item becomes the last and vice-versa). You call a method using a period (.) structure like the following:

«objectName».«methodName»(«list of arguments, if any»)

For comparison, the syntax we have already seen for calling functions was

«functionName»(«list of arguments, if any»)

Here is an example of calling the reverse method on a list.

Example
Reversing a list.

An example of a method which takes an argument is str.startswith:

Example
Some string methods.

Many Methods

Below we mention the most common methods for the string and list classes. These mostly perform tasks that you should be able to write yourself, but using standard methods has the benefit of making your code easier for others to read and edit.

Lists

These methods do not alter the list:

  • list.index(X): find X in the list. Specifically, this returns an i such that list[i]==X by searching all items. The lowest possible i is returned. If X doesn't exist in the list, a ValueError is caused.
    • X in list returns True if X is an element of list, otherwise False. Using this can avoid a ValueError. (Note in is an operator, not a method.)
  • list.count(X): returns a count of how many times X appears in the list

Example
List methods.

These methods alter the list:

  • list.append(X) adds X to the end of the list
  • list.insert(i, X) adds X at position i
  • list.extend(L) adds a list L of items to the end
  • list.remove(X) removes the first occurence of X
  • list.pop(i) deletes & returns item list[i], while list.pop() deletes & returns the last item
  • del list[i] deletes the ith item of list (Note this is a "del statement", not a method)
  • list.reverse() reverses the list
  • list.sort() sorts the list

All methods above except pop return None. Some of these functions can also be called with slightly different arguments; for complete details see the section on list methods in the Python documentation. Lists also support complex subranges called "slices" which permit insertion and deletion of entire sublists, similar to the string[x:y:z] notation we saw in previous lessons.

Coding Exercise: The Replacements
Using index and other list methods, write a function replace(list, X, Y) which replaces all occurrences of X in list with Y. For example, if L = [3, 1, 4, 1, 5, 9] then replace(L, 1, 7) would change the contents of L to [3, 7, 4, 7, 5, 9]. To make this exercise a challenge, you are not allowed to use []
Note: you don't need to use return. Hint
Enter testing statements like print(myfunction("test argument")) below.

Strings

Just like with lists, you can use inindex and count with strings. They are even more powerful, since they work with substrings too and not just finding individual characters:

  • S in T is a bool indicating whether string S is a substring of string T
  • S.index(T) finds the first index of S where T is a substring
  • S.count(T) gives the number of nonoverlapping occurrences of T as a substring of S

Example
Calling index and count on strings.

Here are some of the most commonly useful str methods:

  • Letter case: capitalize, lower, upper, islower, isupper
  • Characters: isalpha, isdigit
  • Padding: center, ljust, rjust; strip will erase padding
  • Substrings: endswith, startswith, find, replace
  • Parsing: split, splitlines

We will introduce these in more detail when needed. A complete detailed list of string methods is given in the Python documentation.

Strings are immutable. We mentioned list.reverse() which changes a list by reversing it, but there is no str.reverse() method. This is because string objects cannot be modified once they are created. In lesson 17 we explain a bit more about this.

Here is an example of a string method: S.replace(old, new) returns a modified version of S where every occurrence of substring old has been replaced by new. This creates a new string without altering the old one:

Example
Example: replace returns a new string, and doesn't modify the original.

For the next exercise, the following methods are useful:

  • str.replace, which we just described
  • the boolean method str.isalpha() which gives True if str is a string (or character) made of letters only
  • the boolean method str.isdigit() which gives True if str is a string (or character) made of digits only
  • str.upper() which returns a version of str converted to upper case.

Coding Exercise: Exact Postage
Define a function postalValidate(S) which first checks if S represents a postal code which is valid:

  • first, delete all spaces;
  • the remainder must be of the form L#L#L# where L are letters (in either lower or upper case) and # are numbers.

If S is not a valid postal code, return the boolean False. If S is valid, return a version of the same postal code in the nice format L#L#L# where each L is capital.

Enter testing statements like print(myfunction("test argument")) below.

The rest of this lesson is a bit technical and not required knowledge for the remaining lessons.

More About Objects

As you learn more about Python, you will encounter more classes than just strings and lists. Others which you are likely to find useful are file objects, sets, and dictionaries. They all have many useful methods. You can ask Python for all of the methods of a given object using the dir function:

Example
The methods of a str. Note that startswith is one of the outputs.

Looking at the properties of an object is called introspection. Everything in Python is allowed to have methods:

Example
The methods and data attributes of an int.

Some of the entries in dir are actually member variables instead of methods, for example int.denominator is a number and not a function. Technically, functions are objects in Python, so member functions are a special case of member variables.

You can do introspection on modules too. If you import math and then call dir(math) then you'll get a list of everything in the math module, including the number pi and the function sqrt.

Why Objects?

Why do we have methods like S.index(T) instead of just a simple function call like index(S, T)? That is to say, why do we have the object S and the method str.index() at all?

The major advantages of objects become clearer as you start programming with more complex and varied types of data. Each type of object (i.e., the str class) represents both the underlying data being stored (e.g., a sequence of characters and its length) and the types of operations that can be performed on it (e.g., converting to upper case or producing a substring). A more complex example are file objects: they represent the name of the file being opened, your current position in the file, and methods to read and write to them. You can even define your own data types!

This general approach is called "object-oriented programming" (OOP). Some of its benefits are:

  • organization: Everything from the math module can be accessed by math.«name» syntax, avoiding the potential for overwriting existing variable names in your program.
  • encapsulation: Just like a program can work with several strings or several files at the same time, you can work with many distinct copies (instances) of the data type defined by any other class.
  • re-use: Once you've defined a data type (like str) or a library of methods (like math) you can re-use it over and over again, or give it to other people to use.
  • debugging: Earlier, we saw how writing a function prevents the need for having many copies of similar code, which makes debugging easier. Writing all functions associated with a data type in a single place (the class definition) has the same effect.
  • relations between classes: Python knows that the index method can mean one thing for a string and something else for a list. Likewise, not only can Python read and write files on your computer, but it can also read and write data on the Internet. In both cases (character or list sequences, and local or remote files) the related classes can be handled in a uniform way using the concept of inheritance.

In the rest of CS Circles we'll only be using objects and methods; you can learn more about creating your own classes later on (see the Resources page).

The next three lessons can be completed in any order, and they give a variety of challenges combining the topics from earlier lessons.