1.3 Methods

Working with Variables

Each data type has its own methods. In object-oriented programming (OOP), a method is a function that is associated with a class. In Python, everything is an object (or class, see chapter 6 for more on this topic), so every data type has its own methods because each type is defined as a class. Basically, think of a class as any object that has its own attributes and abilities. The abilities are the methods, the things we can do with the object. Another way of saying this is that the methods are the functions that are inherent to the object. They are ways of manipulating or interrogating the data type. The point here is that methods are not limited to data types. They are inherent to objects in general, but the methods for data types help us manipulate the data in a way that is specific to that data type.

For any method, we use the dot operator to access it. The syntax is object.method(). In the case of data types, the object is the data itself.

I will provide some basic examples of most important simple methods for each data type. These are not exhaustive lists, but they are the most commonly used methods that will be easy for beginners to understand the concepts associated with methods and types.

Note

You do not need to memorize all of these methods. They are here for reference. You will learn the most commonly used methods as you work with Python. The best way to learn is to practice using them in your own code.

String Methods

String methods are a good place to start because they are the most commonly used methods in Python. Strings are sequences of characters, and they have many methods that allow us to manipulate them. See the Python documentation for more information on strings. Here are some of the most commonly used string methods:

  • capitalize(): Converts the first character to upper case
  • casefold(): Converts string into lower case
  • center(): Returns a centered string
  • count(): Returns the number of times a specified value occurs in a string
  • length(): Returns the length of a string
  • index(): Searches the string for a specified value and returns the position of where it was found first. Note that indexes are 0-based numbers, so the first location is location 0.
string1= "hello, world!"
print('capitalize(): ', string1.capitalize())
print('casefold(): ', string1.casefold())
print('center(): ', string1.center(20))
print('count(): ', string1.count('l'))
print('length(): ', len(string1))
# index will return 2 because the h is at index 0 and the e is at index 1
print('index(): ', string1.index('l')) 
capitalize():  Hello, world!
casefold():  hello, world!
center():     hello, world!    
count():  3
length():  13
index():  2
  • len(string): Returns the length of the string. Example: "something" → 9.
  • string.count("s"): Counts the occurrences of a specific character in the string. Example: "something" → 1.
  • min(string): Returns the smallest character in the string (based on ASCII value). Example: "something" → "e".
  • max(string): Returns the largest character in the string (based on ASCII value). Example: "something" → "t".
  • "some" * 3: Repeats the string "some" three times. Example: "some" → "somesomesome".
first_name = "Nathan"
last_name = "Michalewicz"
print("Length of first name is", len(first_name))
print("Count of 'a' in first name is", first_name.count("a"))
print("Min of first name is", min(first_name))
print("Max of first name is", max(first_name))
print("first name * 3 is", first_name * 3)
Length of first name is 6
Count of 'a' in first name is 2
Min of first name is N
Max of first name is t
first name * 3 is NathanNathanNathan

Methods for Splitting and Joining Strings

  • string.join(iterable): Combines elements of an iterable (e.g., a list) into a single string, using the specified string as a separator.
    • Example: " ".join(["a", "b", "c"]) → "a b c".
    • Explanation: The " " acts as the separator, joining the elements of the list into a single string with spaces between them.
  • string.partition(substring): Splits the string into three parts: the part before the first occurrence of the substring, the substring itself, and the part after it.
    • Example: "something".partition("o") → ("s", "o", "mething").
    • Explanation: This method always returns a 3-tuple, even if the substring is not found (in which case the middle element is an empty string).
  • string.rpartition(substring): Similar to partition(), but splits the string at the last occurrence of the substring instead of the first.
    • Example: "something".rpartition("o") → ("so", "m", "ing").
    • Explanation: This method is useful when you need to split from the end of the string.
  • string.split(separator): Splits the string into a list of substrings based on the specified separator.
    • Example: "a b c".split(" ") → ["a", "b", "c"].
    • Explanation: The separator determines where the string is split. If no separator is provided, it splits at whitespace by default.
  • string.split(separator, max): Splits the string into a list of substrings, but limits the number of splits to max.
    • Example: "a b c d".split(" ", 2) → ["a", "b", "c d"].
    • Explanation: The max parameter controls how many splits are performed, leaving the rest of the string unsplit.
  • string.rsplit(separator, max): Similar to split(), but performs the splits starting from the end of the string.
    • Example: "a b c d".rsplit(" ", 2) → ["a b", "c", "d"].
    • Explanation: This is useful when you need to split from the right side of the string.
  • string.splitlines(): Splits the string into a list of lines, breaking at line boundaries (\n, \r, etc.).
    • Example: "line1\nline2\nline3".splitlines() → ["line1", "line2", "line3"].
    • Explanation: This method is helpful for processing multi-line strings, as it automatically handles different types of line breaks.
lname = "Michalewicz"
fname = "Nathan"
s = "a b c d e f g"
lines = "a\nb\nc\nd\ne\nf\ng"  # \n is a newline character
print(fname.partition("a"))
print(fname.rpartition("a"))
print(s.split(" ", 3))
print(s.rsplit(" ", 3))
print(lines.splitlines())
('N', 'a', 'than')
('Nath', 'a', 'n')
['a', 'b', 'c', 'd e f g']
['a b c d', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']

String Alignment and Padding methods

We can manipulate the padding and alignment of strings through a number of methods. Here are a few.

  • string.ljust(width): Left-aligns the string within a field of the specified width, padding the right side with spaces.
    • Example: "a".ljust(10) → "a ".
  • string.rjust(width): Right-aligns the string within a field of the specified width, padding the left side with spaces.
    • Example: "a".rjust(10) → " a".
  • string.center(width): Centers the string within a field of the specified width, padding both sides with spaces.
    • Example: "a".center(10) → " a ".
  • string.zfill(width): Pads the string with zeros on the left until it reaches the specified width.
    • Example: "a".zfill(10) → "000000000a".
  • string.center(width, fillchar): Centers the string within a field of the specified width, padding both sides with the specified fillchar.
    • Example: "a".center(10, "-") → "----a-----".
  • string.expandtabs(tabsize): Replaces tab characters (\t) in the string with spaces, using the specified tabsize for the width of each tab.
    • Example: "a\tb".expandtabs(10) → "a b".
  • string.strip(): Removes leading and trailing whitespace (or specified characters) from the string.
    • Example: " a ".strip() → "a".
  • string.lstrip(): Removes leading whitespace (or specified characters) from the string.
    • Example: " a ".lstrip() → "a ".
  • string.rstrip(): Removes trailing whitespace (or specified characters) from the string.
    • Example: " a ".rstrip() → " a".
s = "a"
print("ljust", s.ljust(10))
print("rjust", s.rjust(10))
print("center", s.center(10))
print("zfill", s.zfill(10))
print("center", s.center(10, "-"))
print("expandtabs", "a\tb".expandtabs(10))
print(".strip", "  a  ".strip())
print(".lstrip", "  a  ".lstrip())
print(".rstrip", "  a  ".rstrip())
ljust a         
rjust          a
center     a     
zfill 000000000a
center ----a-----
expandtabs a         b
.strip a
.lstrip a  
.rstrip   a

Find/Replace Methods

Strings have several methods for finding and replacing substrings. These methods are useful for searching for specific characters or patterns within a string and replacing them with other characters or strings.

  • string.find(substring): Searches for the first occurrence of the specified substring in the string and returns its lowest index. Returns -1 if the substring is not found.
    • Example: "something".find("s") → 0.
  • string.rfind(substring): Searches for the last occurrence of the specified substring in the string and returns its highest index. Returns -1 if the substring is not found.
    • Example: "something".rfind("s") → 0.
  • string.index(substring): Searches for the first occurrence of the specified substring in the string and returns its lowest index. Raises a ValueError if the substring is not found.
    • Example: "something".index("s") → 0.
  • string.rindex(substring): Searches for the last occurrence of the specified substring in the string and returns its highest index. Raises a ValueError if the substring is not found.
    • Example: "something".rindex("s") → 0.
  • string.replace(old, new): Replaces all occurrences of the old substring with the new substring in the string.
    • Example: "something".replace("s", "t") → "tomething".
  • string.replace(old, new, count): Adding a third argument replaces up to count occurrences of the old substring with the new substring in the string.
    • Example: "ssss".replace("s", "t", 3) → "ttts".
s = "Nathan"
print("find: ", s.find("a"))
print("rfind: ", s.rfind("a"))
print("index: ", s.index("a"))
print("rindex: ", s.rindex("a"))
print("replace: ", s.replace("a", "o"))
print("replace: ", s.replace("a", "o", 1))
find:  1
rfind:  4
index:  1
rindex:  4
replace:  Nothon
replace:  Nothan

Methods for Input Validation

Input validation is a way to ensure that the input (or data)is in the correct data type. This is especially important when accepting user input. There are many ways to validate input. The most common way is to use the is functions. These functions are built into Python and return a boolean value.

The typical process is to accept an input value validate its type and then process it. If the input is not correct, you can raise an error or ask the user to input the correct value. If you try to process the input data before validating it, you may get an error, and errors stop the program because Python reads synchronously from top to bottom. That means the program will stop completely.

Below, you can see the different is functions that are available in Python.

Input Validation Definition
str.isalpha() True if all alphabetic
str.isdigit() True if all digits
str.isalnum() True if all alphanumeric
str.isdecimal() True if all 0-9
str.isnumeric() True if all numeric
str.islower() True if all lowercase
str.isupper() True if all uppercase

Some of these are self-explanatory, others are less clearly named. Naming is very important in Python, and you should take naming conventions seriously. Some of these are exemplary as to why. For example, isalpha() is a very clear name. It is easy to understand that it checks if the string is alphabetic. However, isdecimal() is less clear. Conventional English would indicate that this tests if the string includes a float or a decimal such as 2.0. But that is not the case. If it were, it would be named isfloat() (which doesn’t exist because the period will always be evaluated as non-numeric). Instead, isdecimal() checks if the string is a decimal number, such as 2 or 90. It checks if all the characters are numbers (0-9) without any other type of character.

Working with Integers and Floats

Numbers, while an object, typically do not have methods associated with them. Instead, they have functions that can be applied to them.

Mathematical Operators

Operator Name Example
+ Addition 1 + 2 outputs 3
- Subtraction 2 - 1 outputs 1
* Multiplication 2 * 2 outputs 4
/ Division 4 / 2 outputs 2
% Modulus: takes the remainder of the first number divided by the second 9 % 2 outputs 1
** Exponentiation: raises the first number to the power of the second 4 ** 2 outputs 16

Addition, subtraction, multiplication, and division are straightforward. The other two are a little different. The modulus operator returns the remainder of the division of the first number by the second. This can be helpful to find out if a number is divisible by another. The exponentiation operator raises the first number to the power of the second number.

Built-in Number Functions

Python provides several built-in functions that can be applied to numbers. These functions are not methods, but they are useful for performing mathematical operations on numbers.

  • abs(x): Returns the absolute value of x, which is the distance of x from zero, regardless of its sign.
    • Example: abs(-5) → 5.
  • max(x, y, z, ...): Returns the largest value among the provided arguments.
    • Example: max(1, 5, 3) → 5.
  • min(x, y, z, ...): Returns the smallest value among the provided arguments.
    • Example: min(1, 5, 3) → 1.
  • pow(x, y): Returns x raised to the power of y. Equivalent to x ** y.
    • Example: pow(2, 3) → 8.
  • round(x [, n]): Rounds x to the nearest integer. If n is specified, it rounds x to n decimal places.
    • Example: round(5.678, 2) → 5.68.

Example

number = -4.12312
l = [1, 2, 3, 4, 5]
t = (1, 2, 3, 4, 5)
print("abs: ", abs(number))
print("max: ", max(l))
print("max: ", max(t))
print("min: ", min(l))
print("pow: ", pow(number, 3))
print("round: ", round(number, 2))
abs:  4.12312
max:  5
max:  5
min:  1
pow:  -70.09352873155534
round:  -4.12

math Module

There is also the math module, which provides additional mathematical functions. You need to import it to use it. The math module provides access to mathematical functions like trigonometric functions, logarithmic functions, and more advanced mathematical operations. They are not methods, but functions that can be applied to numbers.

import math
  • math.copysign(x, y): Returns x with the sign of y. This means the magnitude of x is preserved, but its sign is replaced with the sign of y.
    • Example: math.copysign(5, -3) → -5.
  • math.fabs(x): Returns the absolute value of x as a floating-point number.
    • Example: math.fabs(-5.5) → 5.5.
  • math.factorial(x): Returns the factorial of x, which is the product of all positive integers up to x. Only works for non-negative integers.
    • Example: math.factorial(5) → 120 (since 5 * 4 * 3 * 2 * 1 = 120).
  • math.floor(x): Returns the largest integer less than or equal to x. This effectively rounds x down to the nearest whole number.
    • Example: math.floor(5.9) → 5.
  • math.ceil(x): Returns the smallest integer greater than or equal to x. This effectively rounds x up to the nearest whole number.
    • Example: math.ceil(5.1) → 6.
  • math.fmod(x, y): Returns the remainder of dividing x by y, using the same sign as x. Unlike the % operator, it handles floating-point numbers.
    • Example: math.fmod(7.5, 2) → 1.5.

Example

import math  # IMPORTANT!!!! import math

x = -4
y = 3
z = 4.712

print("copysign: ", math.copysign(x, y))
print("fabs: ", math.fabs(x))
print("factorial: ", math.factorial(5))
print("floor: ", math.floor(z))
print("ceil: ", math.ceil(z))
copysign:  4.0
fabs:  4.0
factorial:  120
floor:  4
ceil:  5

If you want more information on the math module, you can check the Python documentation.

List Methods

Similarly as strings, lists have methods that allow us to manipulate the data in the list. See the Python documentation for more information on lists. These are but a few of the most commonly used methods for lists.

  • append(): Adds an element at the end of the list
  • clear(): Removes all the elements from the list
  • copy(): Returns a copy of the list
  • count(): Returns the number of elements with the specified value
  • extend(): Add the elements of a list (or any iterable), to the end of the current list
  • index(): Returns the index of the first element with the specified value
  • insert(): Adds an element at the specified position
  • pop(): Removes the element at the specified position
  • remove(): Removes the first item with the specified value
  • reverse(): Reverses the order of the list
list1 = ["apple", "banana", "cherry"]

print('append(): ', list1.append('orange'))
print('clear(): ', list1.clear())
print('copy(): ', list1.copy())
print('count(): ', list1.count('apple'))
print('extend(): ', list1.extend(['apple', 'banana']))
print('index(): ', list1.index('apple'))
print('insert(): ', list1.insert(1, 'orange'))
print('pop(): ', list1.pop(1))
print('remove(): ', list1.remove('apple'))
print('reverse(): ', list1.reverse())
append():  None
clear():  None
copy():  []
count():  0
extend():  None
index():  0
insert():  None
pop():  orange
remove():  None
reverse():  None

The del Statement

The del statement is not a method, but it is a way to remove an element from a list. It can be used to delete an element at a specific index or to delete the entire list. Unlike pop(), del does not return the removed element. It simply removes it from the list. The del statement can also be used to delete entire lists or slices of lists following typical Python slicing syntax.

list1 = ["apple", "banana", "cherry"]
del list1[1]  # Deletes the element at index 1
print("After del: ", list1) 
del list1[:]  # Deletes all items in the list
print("After del list1: ", list1)  
After del:  ['apple', 'cherry']
After del list1:  []

Tuple Methods

Python documentation on tuples and their methods

Tuples are immutable sequences, meaning that once they are created, their elements cannot be changed. This characteristic minimizes the number of methods available to them, but they do have a few methods that allow us to work with them.

  • count(): Returns the number of times a specified value occurs in a tuple.
  • index(): Searches the tuple for a specified value and returns the position of where it was found first. Note that indexes are 0-based numbers, so the first location is location 0.
tuple1 = ("apple", "banana", "cherry")

print('count(): ', tuple1.count('apple'))
print('index(): ', tuple1.index('banana'))
count():  1
index():  1

Set Methods

Sets are unordered collections of unique elements. They have methods that allow us to perform set operations like union, intersection, and difference. See the Python documentation for more information on sets. Some of the most commonly used methods for sets are:

  • add(): Adds an element to the set
  • clear(): Removes all elements from the set
  • copy(): Returns a shallow copy of the set
  • difference(): Returns a set containing the difference between two or more sets
  • difference_update(): Removes the elements of another set from the current set
  • discard(): Removes an element from the set if it is a member. If not a member, it does nothing
  • intersection(): Returns a set containing the intersection of two or more sets.
  • intersection_update(): Updates the current set to be the intersection of itself and another set
  • isdisjoint(): Returns True if two sets have a null intersection (i.e., no common elements)
  • issubset(): Returns True if the current set is a subset of another set.
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "cherry", "date"}
print('add(): ', set1.add('orange'))
print('copy(): ', set1.copy())
print('difference(): ', set1.difference(set2))
print('difference_update(): ', set1.difference_update(set2))
print('discard(): ', set1.discard('apple')) 
print('intersection(): ', set1.intersection(set2))
print('intersection_update(): ', set1.intersection_update(set2))
print('isdisjoint(): ', set1.isdisjoint(set2))
print('issubset(): ', set1.issubset(set2))
print('clear(): ', set1.clear())  
add():  None
copy():  {'cherry', 'orange', 'banana', 'apple'}
difference():  {'apple', 'orange'}
difference_update():  None
discard():  None
intersection():  set()
intersection_update():  None
isdisjoint():  True
issubset():  True
clear():  None

Dictionary Methods

Dictionaries are unordered collections of key-value pairs. They have methods that allow us to manipulate the data in the dictionary. See the Python documentation for more information on dictionaries. Some of the most commonly used methods for dictionaries are:

  • clear(): Removes all elements from the dictionary
  • copy(): Returns a shallow copy of the dictionary
  • get(): Returns the value for a specified key if it exists, otherwise returns None or a specified default value if provided as the second argument.
  • items(): Returns a view object that displays a list of a dictionary’s key-value tuple pairs.
  • keys(): Returns a view object that displays a list of all the keys in the dictionary.
  • values(): Returns a view object that displays a list of all the values in the dictionary.
  • pop(): Removes the specified key and returns the corresponding value. Raises a KeyError if the key does not exist.
  • popitem(): Removes and returns the last inserted key-value pair as a tuple. If the dictionary is empty, it raises a KeyError.
dict1 = {"name": "Nathan", "age": 30, "city": "New York"}
print("copy(): ", dict1.copy())
print("get(): ", dict1.get("name"))
print("items(): ", dict1.items())
print("keys(): ", dict1.keys())
print("values(): ", dict1.values())
print("pop(): ", dict1.pop("age"))  # Removes 'age' key and returns its value
print(
    "popitem(): ", dict1.popitem()
)  # Removes and returns the last inserted key-value pair
print("updated dict1 from pop and popitem(): ", dict1)
print("clear(): ", dict1.clear())
copy():  {'name': 'Nathan', 'age': 30, 'city': 'New York'}
get():  Nathan
items():  dict_items([('name', 'Nathan'), ('age', 30), ('city', 'New York')])
keys():  dict_keys(['name', 'age', 'city'])
values():  dict_values(['Nathan', 30, 'New York'])
pop():  30
popitem():  ('city', 'New York')
updated dict1 from pop and popitem():  {'name': 'Nathan'}
clear():  None

Notice that the pop() method removes a specified key and returns the removed item, while popitem() removes the last inserted key-value pair (and also returning it). This is useful when you want to remove an item without knowing its key.

Random Functions

Python also provides a random module that allows you to generate random numbers and perform random operations. This is particularly useful in data analytics for tasks like sampling, shuffling data, or generating random test cases. The random module includes various functions to generate random numbers, shuffle lists, and set seeds for reproducibility.

  • random.choice(iter): Selects and returns a random element from the given iterable (e.g., a list or tuple).
    • Example: random.choice([1, 2, 3]) → 2 (randomly chosen).
  • random.randint(x, y): Returns a random integer between x and y (inclusive, meaning that it includes both the low number and the high number).
    • Example: random.randint(1, 10) → 7.
  • random.random(): Returns a random floating-point number between 0 and 1.
    • Example: random.random() → 0.7345.
  • random.randrange(x, y, z): Returns a random integer between x and y (exclusive), stepping by z. The third argument is optional.
    • Example: random.randrange(0, 10, 2) → 4.
  • random.shuffle(iter): Shuffles the elements of the given iterable in place, modifying the original iterable.
    • Example: random.shuffle([1, 2, 3]) → [3, 1, 2] (order randomized).
  • random.seed(x): Sets the seed for the random number generator, ensuring reproducible results. In other words, if you set the seed of the random generator, the sequence of randomly generated numbers will always be the same. This is true regardless of when or where the code is run as long as the seed is set the same. This allows you to recreate the same random behavior consistently.
    • Example: random.seed(42) → Subsequent random calls will produce the same sequence of values.

Example

import random  # IMPORTANT!!!! import random

l = [1, 2, 3, 4, 5]
r = []
print("choice: ", random.choice(l))
print("randint: ", random.randint(1, 10))
print("random: ", random.random())
print("randrange: ", random.randrange(1, 10, 2))
random.shuffle(l)
print("shuffle: ", l)
print("seed: ", r)
choice:  4
randint:  6
random:  0.05176517686858151
randrange:  3
shuffle:  [2, 5, 3, 1, 4]
seed:  []

For more information on the random module, you can check the Python documentation.