Quick Reference Pages

Common Methods Reference

In addition to Python's built-in functions, Python's basic types like strings, lists, and dictionaries have more functions attached to them as "methods" that you'll need to learn about. A "method" is just a function that's attached to a type; to call it we write a specific value of that type (maybe as a variable) and then a period, followed by the method name and any additional parameters. The value before the period always serves as an implicit first parameter to the method call. This is what that looks like:

response = input("Do you like ice cream? ")
lowercase = response.lower()
affirmative = lowercase.startswith('y')

Here we used two methods of strings: (lower)[#.lower] and (startswith)[#.startswith]. The lower method doesn't need any additional arguments beyond the value that it's attached to (but the parentheses are still required to actually call the method), while the startswith method needs one additional argument (which we put inside the parentheses after the method name, just like when we call a regular function). In both cases, the thing before the period (response or lowercase) is functioning like an extra argument to the method (e.g., what are we getting a lowercase version of? The response value).

Why are some functions just built-in and others methods of a particular type? That's because when a function can only work with a specific type of data, making it a method helps prevent errors, because you can't accidentally try to use it with another kind of value. It also helps organize things conceptually. For example, len is a built-in function because it can work with any type of sequence, including strings, lists, etc. On the other hand, lower is a method, because it only makes sense in the context of strings.

The table below includes very brief reference explanations for the common methods that we'll use in this class, along with tiny examples of how they can be used correctly (feel free to paste those examples into your Python shell to see what the results are and double-check your understanding). This is meant as a quick reference guide, not a thorough explanation of all of the details. Remember you can always use the `help function to get more information about another function, in the case of methods, you could write something like help(str.lower) or help(list.append) because you still need to reference a particular type to get access to a method.


Function Effect Example(s)
.lower / .upper / .capitalize These methods return a string based on the string they're attached to but with different case for some letters. .lower returns the same string in all-lower-case, .upper in all-upper-case, and .capitalize returns the string with the first letter in upper case and the rest in lower case. These functions don't modify the original string (that's impossible since strings are immutable), but instead they return a new, similar string. 'abc'.capitalize()
r = input('Ok? [y/n] ')
n = r.lower()
.startswith / .endswith These methods return booleans (True or False) based on whether the string they're attached to starts or ends with another string (supplied as an argument after the method name). To qualify, the first (or last) letters of the string the method is attached to must be exactly the same as the provided argument. 'abc'.startswith('ab') 'abc'.endswith('b')
.isspace / .isalpha / .isdigit / .isnumeric / .isalnum These methods also return booleans, based on what kind of characters are in the string they're attached to. .isspace returns True if every character in the string is a white-space character (like a space, or a tab, or even a new-line). .isalpha returns true if every character in the string is an 'alphabetic' character, including characters in non-Latin alphabets, but excluding things like spaces, numbers, punctuation, etc. .isdigit returns true if every character is an Arabic numeral (i.e., 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), whereas .isnumeric returns true if every character is a numeric character, including Arabic numerals and others like 'ⅶ' or '一'. Finally, .isalnum returns true if every character is either alphabetic OR numeric. Each of these functions returns False for an empty string. ' \n\t'.isspace()' 'Otter獭'.isalpha() '123'.isdigit() '一二三四'.isnumeric() 'one23'.isalnum()
.format This is a very powerful method that lets you construct a string by placing other Python values inside of a template string. Wherever a pair of curly braces appears in the template, an additional parameter will be required, and the value of that parameter will be converted to a string and will replace the corresponding curly brace pair within the template to produce the result. For example: '{} golden {}'.format(5, 'rings') will return the string '5 golden rings'. Compared to concatenating strings, .format usually makes it easier to control the spacing around values that you're building into a larger string, and like print, it converts values to strings automatically. .format also has advanced capabilities beyond those described here. '{}-{} {}.'.format("a", "b", "c") 'There are {} matching lines.'.format(nmatches)
.join Builds a string by combining multiple strings from a sequence (the argument) into a single string, with a 'glue' string (the string that .join is attached to) placed in between each pair of items. If the sequence you give it is empty, it will return an empty string, and if the sequence contains just a single string, you'll get just that string back. The items in the sequence you supply must be strings (but of course, strings themselves count as sequences of one-character strings). ', '.join(['a', 'b', 'c']) '-'.join('123')
.split Returns a list of strings by splitting up the string it's attached to. If no arguments are given, the attached string is split wherever one or more white-space characters appear. If an argument is given, it must be a string, and anywhere that that particular pattern occurs within the string that .split is attached to, the string will be split. The patterns used to split are removed from the results. If the split pattern doesn't appear in the string to be split, a list containing that entire string is the result. If the split pattern appears at the start or end of the string, the resulting list will include an empty string at the beginning or end. 'A few words.'.split() 'banana'.split('a')
Function Effect Example(s)
.append Modifies the list that it's invoked on (i.e., the list it's attached to) by adding a single element as the new last element of the list. The element to be added is supplied as an argument. Use .extend instead if you want to add multiple elements at once. This method doesn't return anything, so you can't use it productively with = or return. It's usually more appropriate to use it as a separate step and then return or assign the list that you just modified.
nums = [1, 2]
.insert Modifies the list that it's invoked on by inserting a single element before the specified index (the two arguments are the index to insert at, followed by the value to insert). If the index you provide is greater than or equal to the length of the list, the element will be inserted at the end. Except in that case, after the insertion is done the element that was inserted will be at the index that it was inserted before (because the old element there and all subsequent elements get pushed one index later). Like .append, this function doesn't return anything.
nums = [5, 6]
nums.insert(0, 4)
.pop Modifies the list that it's invoked on by removing the element that's at the specified index (the only argument). If no argument is supplied, it removes the last element from the list. An IndexError will happen if attempting to pop at an index that doesn't exist, including attempts to pop from an empty list. This method returns the value that it removes. If you just want to know the value at a specific index, just use [] to access it; use .pop only if you need to remove an item.
nums = [1, 2, 3]
last = nums.pop()
first = nums.pop(0)
.extend Modifies the list that it's invoked on by adding multiple elements from another sequence at the end. The sequence of elements to add is provided as an argument, and will not be modified. Note that strings count as sequences of individual letters, but extending a list with a string is usually not what you want to do, since each letter would be added as a separate element in the list you're extending.
nums = [1]
nums.extend([2, 3])
.index Returns the index of the first element in the list it's attached to which matches the argument it's given. A ValueError will happen if there are no matching elements (matching is determined by ==). If there are multiple matches, only the index of the first match is returned. In particular, you CANNOT depend on .index to tell you your position in a list during a loop, because if that loop contains multiple copies of some values, .index won't give you the correct results for copies after the first. If you need to know your index within a loop, convert your loop to an index loop.
nums = [4, 5, 6, 5]
where = nums.index(5)
.remove Modifies the list that it's invoked on by removing the first element of the list that matches the supplied argument. This method starts at the beginning of the list and moves along until it finds an element that's equal to the argument given, which it then removes. A ValueError will result if there are no matching elements in the list, you can use the in operator to test for that beforehand. Note that if there are multiple matching items, only the first will be removed. Be careful of the difference between .pop and .remove. In most cases, using .pop is more exact.
nums = [1, 2, 3, 2]
Function Effect Example(s)
.keys Returns a collection containing just the keys of the dictionary. Note that it's a collection, not a sequence: it doesn't have an established order (although it has an implicit order) and it cannot be indexed (although it can be iterated over).
data = {'a': 1, 'b': 2}
.values Returns a collection containing just the values of the dictionary. Note that it's a collection, not a sequence, just like the result of .keys.
data = {'a': 1, 'b': 2}
.items Returns a collection containing key/value pairs from the dictionary. Like .keys and .values, it's not a sequence. Each item in the collection is a tuple that holds a key and the associated value for that key.
data = {'a': 1, 'b': 2}
.get Returns the value associated with a key in the dictionary (the key is provided as an argument). Unlike the [] operator, if the specified key isn't in the dictionary, instead of raising an error it will return None. If two arguments are given, the second is used as a default instead of None. A more deliberate approach than using .get is to use the in operator to check for the presence of a key and then use either the [] operator to get the value or use a default value using a conditional.
data = {'a': 1, 'b': 2}
print(data.get('c', 'nope'))
.pop Removes a key/value pair from the dictionary, specified using the key as an argument. Returns the value part of the pair. Raises a KeyError if the target key isn't in the dictionary (use the in operator to check for that).
data = {'a': 1, 'b': 2}
.update Updates multiple values in the dictionary at once by copying over key/value pairs from another dictionary (provided as an argument). Only the dictionary it's invoked on is modified. For each key in the dictionary being updated from, the value for that key in the dictionary being modified will be set to the value that's in the dictionary being updated from, regardless of whether that key already had a value in the dictionary being modified. In other words, new key/value pairs are added where necessary, and where a key already exists, its old value is updated.
old = {'a': 1, 'b': 2}
new = {'b': 3, 'c': 4}