Metadata
Title
14: Methods
Category
general
UUID
86f9e95c26db41839d90f1b6a7c01fd0
Source URL
https://cscircles.cemc.uwaterloo.ca/14-methods/
Parent URL
https://cscircles.cemc.uwaterloo.ca/
Crawl Time
2026-03-18T05:14:01+00:00
Rendered Raw Markdown

14: Methods

Source: https://cscircles.cemc.uwaterloo.ca/14-methods/ Parent: https://cscircles.cemc.uwaterloo.ca/

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.

L = [1, 2, 3, 4, 5] L.reverse() print(L)

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

Example

Some string methods.

print('piece of cake'.startswith('pie')) print('red'.startswith('blue'))

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:

Example

List methods.

L = [3, 1, 4, 1, 5, 9] print(L.index(9)) print(L[L.index(3)]) print(L.count(1))

These methods alter 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

You need to create an account and log in to ask a question.

def replace(list, X, Y):

delete this comment and enter your code here

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

More actions... History Reset code to default Help

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:

Example

Calling index and count on strings.

print("marmalade".count("ma")) print("find a substring".index("substring")) print("key" in "monkey")

Here are some of the most commonly useful str methods:

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.

name = 'Bob Jones' newName = name.replace('Bob', 'Robert') print(name) print(newName)

For the next exercise, the following methods are useful:

Coding Exercise: Exact Postage

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

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.

You need to create an account and log in to ask a question.

delete this comment and enter your code here

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

More actions... History Help

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.

myName = 'Jim' print(dir(myName))

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.

x = 42 print(dir(x)) # includes 'bit_length' print(x.bit_length()) # a method of 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:

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.