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 `list`s 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:

- `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](https://cscircles.cemc.uwaterloo.ca/console/?consolecode=L%3D%5B0%2C%201%2C%202%5D%0Aprint%28L.index%283%29%29).
  - `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.

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:

- `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 `i`th 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](http://docs.python.org/py3k/library/stdtypes.html#mutable-sequence-types) 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](https://cscircles.cemc.uwaterloo.ca/7a-strings/) [lessons](https://cscircles.cemc.uwaterloo.ca/12-tips/).

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 `in`, `index` 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.

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

|  |  |  |
| --- | --- | --- |
|  |  |  |

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](http://docs.python.org/py3k/library/stdtypes.html#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:

- `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.

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](https://cscircles.cemc.uwaterloo.ca/console/?consolecode=def%20f%28%29%3A%20return%2042%0Ag%20%3D%20f%0Aprint%28g%28%29%29%0Aprint%28type%28f%29%29) 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.