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.
An example of a method which takes an argument is
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.
These methods do not alter the list:
Xin the list. Specifically, this returns an
list[i]==Xby searching all items. The lowest possible
iis returned. If
Xdoesn't exist in the list, a
X in listreturns
Xis an element of list, otherwise
False. Using this can avoid a
inis an operator, not a method.)
list.count(X): returns a count of how many times
Xappears in the list
These methods alter the list:
Xto the end of the
list.extend(L)adds a list
Lof items to the end
list.remove(X)removes the first occurence of
list.pop(i)deletes & returns item
list.pop()deletes & returns the last item
del list[i]deletes the
ith item of
list(Note this is a "
delstatement", not a method)
list.reverse()reverses the list
list.sort()sorts the list
All methods above except
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.
Just like with lists, you can use
count with strings. They are even more powerful, since they work with substrings too and not just finding individual characters:
S in Tis a bool indicating whether string
Sis a substring of string
S.index(T)finds the first index of
Tis a substring
S.count(T)gives the number of nonoverlapping occurrences of
Tas a substring of
Here are some of the most commonly useful
- Letter case:
capitalize, lower, upper, islower, isupper
center, ljust, rjust;
stripwill erase padding
endswith, startswith, find, replace
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:
For the next exercise, the following methods are useful:
str.replace, which we just described
- the boolean method
stris a string (or character) made of letters only
- the boolean method
stris a string (or character) made of digits only
str.upper()which returns a version of
strconverted to upper case.
|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
Looking at the properties of an object is called introspection. Everything in Python is allowed to have methods:
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
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
mathmodule 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
indexmethod 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.