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 str.startswith:
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): findXin the list. Specifically, this returns anisuch thatlist[i]==Xby searching all items. The lowest possibleiis returned. IfXdoesn't exist in the list, aValueErroris caused.X in listreturnsTrueifXis an element of list, otherwiseFalse. Using this can avoid aValueError. (Noteinis an operator, not a method.)list.count(X): returns a count of how many timesXappears in the list
These methods alter the list:
list.append(X)addsXto the end of thelistlist.insert(i, X)addsXat positionilist.extend(L)adds a listLof items to the endlist.remove(X)removes the first occurence ofXlist.pop(i)deletes & returns itemlist[i], whilelist.pop()deletes & returns the last itemdel list[i]deletes theith item oflist(Note this is a "delstatement", not a method)list.reverse()reverses the listlist.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.
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 Tis a bool indicating whether stringSis a substring of stringTS.index(T)finds the first index ofSwhereTis a substringS.count(T)gives the number of nonoverlapping occurrences ofTas a substring ofS
Here are some of the most commonly useful str methods:
- Letter case:
capitalize, lower, upper, islower, isupper - Characters:
isalpha, isdigit - Padding:
center, ljust, rjust;stripwill 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:
For the next exercise, the following methods are useful:
str.replace, which we just described- the boolean method
str.isalpha()which givesTrueifstris a string (or character) made of letters only - the boolean method
str.isdigit()which givesTrueifstris a string (or character) made of digits only str.upper()which returns a version ofstrconverted 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 dir function:
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 sqrt.
Why Objects?
Why do we have methods like S.index(T) instead of just a simple function call like index(S, T)? Answering this fully would take us into a deep explanation of "object-oriented programming" (OOP). Instead, we just give a taste of what is going on. One nice effect is organization: everything from the math module can be accessed by math.«name» syntax, avoiding the potential for overwriting existing variable names in your program. Second, we want a way for Python to know that "stringone".index("r") means the string version of index, and that [3, 4, 5].index(4) means the list version of index. But, there is a lot of commonality between strings and lists: if you imagine yourself as the inventor of Python, it would be nice to only write most of the built-in functions only once for a general sequence type, and then derive two specialized string and list subtypes with any necessary features. OOP lets you create a new class (subclass), while inheriting the features of an old one (superclass). Then really cool things can happen: if you take a function name defined in the old class, and redefine it, then everyone who calls the function on objects of the new class gets the new definition instead of the old one — even calls defined in inherited methods from the old class! Even if it doesn't seem extremely cool now, know that it can be very handy in practice, especially with large collections of code.
That's it for now! You are ready for the next lesson.


