Python
Library Quick Reference
This page describes the
subset of the Python library that we will use in Programming 1. For
more information, see the official Python
Standard Library reference.
booleans
A bool is a Boolean
value, either False or
True. The function bool(x) converts a value to a bool.
Booleans provide
the following operations:
x or y : logical or
x and y : logical and
not x : logical not
numbers
An int is an integer of arbitrary size. A float is a
floating-point number. The functions int(x) and float(x) convert a
value to an int or float.
These numeric types
provide these operations:
The following built-in functions work on numeric values:
-
- abs(x)
-
Return the absolute value of x.
-
round(x)
-
Return x rounded to the nearest integer.
floats provide this operation:
-
- f.is_integer()
-
Return true if a float represents
an integer.
iterables
An iterable is a series of values that the for
statement can loop over. All sequences (see below) are iterables, and
Python supports various
other kinds of iterables as well (e.g. sets, dictionaries,
text files).
The following operations
work on any iterable:
-
- x in iter
-
True if x is a member of the given iterable. (For strings, however,
s in t returns True if s is a substring of t.)
-
all(iterable)
-
Return True if all elements of an iterable are True.
-
any(iterable)
-
Return True if any elements of an iterable are True.
-
enumerate(iterable)
-
Return an iterable of pairs (i, x), where i is the index of an item
in the given iterable and x is its value.
-
filter(function, iterable)
-
Apply a function to
each element of an
iterable, returning an iterable of all values for which the
function returns True.
-
map(function, iterable)
-
Apply a function to
each element of an
iterable, returning an iterable of the results.
-
max(iter, *, key =
None)
max(arg1, arg2, …, key = None) -
Return the maximum value in an iterable, or in a series of
arguments. If a key function is
specified, it is applied to each value before computing the maximum.
If the iterable is empy, the function raises a ValueError.
-
min(iter, *, key = None)
min(arg1, arg2, …, key = None) -
Return the minimum value
in an iterable, or in a series of arguments. If
a key function is specified, it is applied to each value before
computing the maximum. If the iterable is empy, the function raises
a ValueError.
-
sorted(iter, *, reverse = False, key = None)
-
Return a new sorted list of the items in iter. If 'reverse' is True,
the list will be sorted in reverse order. If a key function is
specified, it is applied to each item to produce a comparison key.
-
sum(iter)
-
Return the sum of values in an iterable.
-
zip(*iterables)
-
Iterate over two or more iterables in parallel, returning an
iterable of tuples. For example, zip(a, b) will produce an iterable
of pairs, each containing an item from a and the corresponding item
from b. zip() stops as soon as it reaches the end of the shortest of
the given iterables.
sequences
Sequences include lists, tuples, ranges, and strings. Their
elements can also be accessed directly by index. Sequences are
iterable, i.e. the 'for' statement can
loop over a sequence's elements.
Sequences support the
following operations:
-
- s[i]
-
Return the i-th
element of s. The first element is s[0]. A negative value of
i indexes from the end of the sequence: s[-1] is the last element,
and s[-2] is the second last.
-
s[i : j]
-
Return a slice of elements from s[i] up to (but not including)
s[j]. Either i or j may be negative to index from the end of the
sequence. If i is omitted, it is 0. If j is omitted, it is len(s).
-
s[i : j : k]
-
Return a slice of elements from s[i] up to (but not including)
s[j], stepping by k.
-
len(s)
-
Return the length of a sequence.
-
reversed(s)
-
Return an iterator over a sequence's elements in reversed order.
-
s + t
-
Concatenate two sequences of the same type. (This operator does
not work on ranges.)
-
n * s (or
s * n)
-
Concatenate s to itself n
times. (This operator does not work on ranges.)
-
s.count(x)
-
Return the number of
occurrences of x in s.
-
s.index(x)
-
Return the index of the first occurrence of x in s. If x is not in
s, this raises a
ValueError
. -
Comparison operators such
as < and > work on some sequences, such as lists, tuples, and
strings. These operators compare sequences lexicographically.
lists
A list is a mutable sequence of arbitrary values. The function
list() converts any sequence to a list.
Lists implement all of the common sequence operations above, plus
these additional operations:
-
- del l[i]
-
Delete the element at index i.
-
del l[i : j]
-
Delete a slice of elements from l[i] up to (but not including)
l[j].
-
l.append(x)
-
Append an element to a list.
-
l.clear()
-
Remove all elements from a list.
-
l.copy()
-
Return a shallow copy of a list.
-
l.extend(seq) (or
l += seq)
-
Append a sequence of elements to a list.
-
l.insert(i, x)
-
Insert x into the list at index i. If i = 0, x is inserted at the
beginning. If i = len(x), x is inserted at the end.
-
l.pop(i = -1)
-
Delete l[i] from the list and return it. If i is not provided, it
defaults to -1, which removes and returns the element at the end of
the list.
-
l.remove(x)
-
Remove the first list element that is equal to x. If there is no
such element, raises a ValueError exception.
-
l.reverse()
-
Reverse the elements of a list
in place.
-
l.sort(*, reverse = False, key = None)
-
Sort a list in place. If
'reverse' is True, the list will be sorted in reverse order. If a
key function is
specified, it is applied to each item to produce a comparison key.
ranges
A range is an immutable sequence of numbers.
-
- range(stop)
range(start, stop, [step]) -
Return a range of integers from start up to (but not
including) stop. If start
is absent, it is 0. If step
is absent, it is 1.
strings
A string is an immutable sequence of Unicode characters. The
function str(x) converts a value to a string.
Strings implement the common sequence operations above, plus these
operations:
-
- chr(i)
-
Convert a Unicode code point (an integer) into a string containing
the corresponding character. The inverse of this function is ord().
-
ord(c)
-
Given a string containing a Unicode character, return the
character's code point, which is an integer. The inverse of this
function is chr().
-
s.endswith(t)
-
True if s ends with
the string t.
-
s.find(sub, [start], [end])
-
Return the lowest index in the string where substring sub is
found within the slice s[start:end], or -1 if not found. start and
end default to 0 and len(s).
-
s.isalpha()
-
True if all characters in s are alphabetic (and there is at least
one character).
-
s.isdigit()
-
True if all characters in s are digits
(and there is at least one
character).
-
s.islower()
-
True if all letters in s are lowercase (and there is at least one
letter).
-
s.isspace()
-
True if all characters in s are whitespace
(and there is at least one
character).
-
s.isupper()
-
True if all letters in s are uppercase (and there is at least one
letter).
-
s.join(seq)
-
Join the strings in the given sequence into a single string,
inserting s between
each adjacent pair in the output.
-
s.lower()
-
Return a copy of a string with all characters converted to
lowercase.
-
s.replace(old, new)
-
Return a copy of s with all instances of old replaced by new.
-
s.rstrip()
-
Remove whitespace from the end of a string.
-
s.split(sep = None)
-
Return a list of words in a
string. By default, strings are separated by arbitrary sequences of
whitespace characters. If sep
is given, it is a delimiter
string that separates words.
-
s.startswith(t)
-
True if s starts with the
string t.
-
s.strip()
-
Remove whitespace from the
beginning and end of a string.
-
s.upper()
-
Return a copy of the string
with all characters converted to uppercase.
The string
module defines these
constants:
-
- string.ascii_lowercase
-
The lowercase letters 'abcdefghijklmnopqrstuvwxyz'.
-
string.ascii_uppercase:
-
The uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
string formatting
A formatted string (f-string) such as f'the
sum is {x + y}'
can contain interpolated values surrounded in
braces. Each interpolated value may be followed by a colon and a
format code. Common format
codes include
b – an integer in binary (base 2)
d – an integer in decimal (base 10)
f – a floating-point number in fixed-point (i.e. not
exponential) notation. This
format code may be preceded by a period ('.') followed by an
integer, which indicates how many digits should
appear after the decimal point.
x – an integer in hexadecimal (base 16)
The 'd' and 'f'
format codes may be preceded by ',' to indicate that digits should be
grouped, producing a string such as '223,566,221'.
Any format code may be preceded by an integer indicating a field
width, which is a minimum number of characters to output. If the
interpolated value is shorter than the field width, Python will
insert spaces at the beginning. For example, f'{23:5d}'
produces ' 23'
(with
three leading spaces). If a field width is preceded by a 0, then
Python inserts zeroes rather than spaces. For example, f'{23:05d}'
produces '00023'
.
sets
A set is a mutable unordered
collection of values. The set() function converts a sequence
to a set.
Sets provide these operations:
-
- len(s)
-
Return the number of elements in s.
-
x in s
-
Test for membership in a set.
-
s.add(x)
-
Add an element to a set.
-
s.clear()
-
Remove all elements from a set.
-
s.discard(x)
-
Remove an element from a set if it is present.
-
s.remove(x)
-
Remove an element from a set. An error will occur if the element is
not present.
-
s & t
-
Return the intersection of two sets.
-
s | t
-
Return the union of two sets.
-
s - t
-
Return the difference of two sets.
-
s <= t
s < t -
Return true if s is a subset (<=) or proper subset (<) of t.
-
s >= t
s > t -
Return true if s is a superset (>=) or proper superset (>) of
t.
dictionaries
A dictionary is a mapping from keys to values. The function
dict(s) converts a sequence to a dictionary.
Dictionaries support these operations:
-
- len(d)
-
Return the number of key/value pairs in a dictionary.
-
d[key]
-
Look up a key, returning the associated value. Raises an error if
the key is not present.
-
d[key] = value
-
Set d[key] to a value.
-
del d[key]
-
Delete a key from a dictionary.
-
key in d
-
Tests to see whether a key is present in a dictionary.
-
d.clear()
-
Remove all items from a dictionary.
-
d.copy()
-
Return a shallow copy of a dictionary.
-
d.get(key, [default])
-
Look up a key and return the associated value, or the
specified default value if the key is absent. If no default
is specified, it is None.
-
d.items()
-
Return a sequence of key-value pairs in a dictionary.
-
d.keys()
-
Return a sequence of keys in a dictionary.
-
d.values()
-
Return a sequence of values in a dictionary.
objects
These built-in functions work on any objects:
-
- isinstance(x, class)
-
Return True if the object x belongs to the given class.
-
type(x)
-
Return an object representing the type (i.e. class) of the object x.
input
and output
-
- input([prompt])
-
Read a line of standard input and return it as a string. If a prompt
string is provided, it is printed before reading. The returned
string will not include a newline character at the end. If the end
of input is reached, this function raises an EOFError.
-
open(filename, mode = 'r')
-
Open a file and return a file object. mode contains one or
more characters indicating how the file is to be accessed. The most
important of these are
-
'r' – open for reading (default)
-
'w' – open for writing. If the file already exists, its existing
contents will be lost!
-
'a' – append to an existing file, or create a new file if the file
does not exist already
-
'b' – binary mode
-
't' – text mode (default)
-
- This method will raise a FileNotFoundError if the file is not
found. FileNotFoundError has an attribute 'filename' containing the
name of the file that was not found.
-
print(*objects, sep = ' ', end
= '\n', file = sys.stdout)
-
Print one or more objects, separated by sep. By default,
print() writes a newline character after each object; to change this
behavior, pass a different value
to the end parameter.
print() writes to standard output by default, but you may pass a
file object to the file
parameter to specify a different destination.
-
The following are methods on file objects:
-
f.close()
-
Call this method to close
a file object when you have finished reading from or writing to it.
Closing after writing is especially important to ensure that all
output will actually be written to the file.
-
f.read(size = -1)
-
Read at most size characters from a file and return them as a
string. If size is -1 (the default value), read the entire
file all at once.
-
f.readline()
-
Read a line from a text
file. The returned string will end with a newline
character ('\n'). If there are no more lines available, the
method returns an empty string ('').
-
f.write(s)
-
Write a string to a text file. This method does not automatically
append a newline to the output.
Also,
any file object
opened for reading in text mode
is an iterable of strings, so you can loop over it with the for
statement. Each string in the iteration will end
with a newline character,
just as if you had read the string with the readline() method.
import collections
-
- collections.defaultdict(f)
-
Create and return a dictionary with default values. If code attempts
to retrieve a missing key from the dictionary, the key will be added
automatically and will be given a value returned by calling the
given function f. The built-in functions
int
and list
(which return 0 and [],
respectively) are useful values for f. -
collections.deque([iter])
-
Create a deque, i.e. a double-ended queue. If an iterable is
provided as an argument, the deque will be initialized with elements
from it.
-
deques support these
operations:
-
d.append(x) – add x to the right side of the queue
-
d.appendleft(x) – add x to the left side of the queue
-
d.pop() - remove a value from the right side of the queue
-
d.popleft() - remove a value from the left side of the queue
-
for x in d – iteration
-
len(d) – number of elements
import csv
-
- csv.DictReader(file, *, delimiter = ',')
-
Create an iterable object that will read from the given CSV
(comma-separated values) file, returning each row as a Python
dictionary. file should be a file object returned by open().
The first line of the file is assumed to contain column names.
-
You may specify a delimiter character that separates fields in each
line; the default delimiter is a comma.
-
csv.DictWriter(file, fieldnames, *, delimiter = ',')
-
Create an object that can write rows to a CSV file. file
should be a file object that was opened for writing. fieldnames
is a list of column names.
-
You may specify a delimiter character that separates fields in each
line; the default delimiter is a comma.
-
dw.writeheader()
-
Write the header line to a CSV file. Typically you will call this
method once after creating a DictWriter.
-
dw.writerow(d)
-
Given a dictionary containing a set of fields, write a line
containing its data to a CSV file.
import datetime
date class
The date
class represents a date such
as January 7, 2024.
-
- date(year, month, day)
-
Create a
date
object with the given
year, month, and day. -
date.today()
-
Create a
date
object representing
today's date. -
d.day
d.month
d.year -
Retrieve the day, month, or year of a
date
object. -
d.isoformat()
-
Convert a date to a string such as '2024-01-07'.
time class
The time
class represents a time such
as 13:18:02.
-
- time(hour, minute, second)
-
Create a
time
object with the given
hour, minute, and second. -
t.hour
t.minute
t.second -
Return the hour, minute, or second of a
time
object.
datetime class
The datetime
class represents a date
and time, such as January 7, 2024 at 13:18:02.
-
- datetime(year, month, day, hour, minute, second)
-
Create a
datetime
object with the given
attributes. -
datetime.now()
-
Create a
datetime
object represent the
current date and time. -
dt.year
dt.month
dt.day
dt.hour
dt.minute
dt.second -
Retrieve the year, month, day, hour, minute, or second of a
datetime
object. -
dt.isoformat()
-
Convert a datetime to a string in a format such as
'2024-01-07T13:18:02'.
import math
-
- math.acos(x)
-
Return the arccosine of x in radians, a value between 0 and π.
-
math.asin(x)
-
Return the arcsine of x in radians, a value between -π/2 and π/2.
-
math.atan2(y, x)
-
Return the arctangent of (y / x) in radians, a value between -π and
π.
-
math.ceil(x)
-
Return x rounded up to the nearest integer.
-
math.comb(n, k)
-
Return n choose k, i.e. the number of ways to choose k items from n
items without repetition and without order.
-
math.copysign(x, y)
-
Return a float that has the magnitude of x but the sign (positive or
negative) of y. (If y is 0, the result will be positive.)
-
math.cos(x)
-
Return the cosine of x in radians.
-
math.dist(p, q)
-
Return the Euclidean distance between points p and q, which may be
tuples with any number of coordinates.
-
math.e
-
The constant e = 2.71828…
-
math.factorial(n)
-
Return n!.
-
math.floor(x)
-
Return x rounded down to the nearest integer.
-
math.inf
-
A floating-point number representing positive infinity.
-
math.isqrt(n)
-
Retrn the integer square root of n, i.e. the square root of n
rounded down to the nearest integer.
-
math.log(x [, base])
-
Return the logarithm of x to the given base. The base defaults to e
if it is not provided.
-
math.pi
-
The constant π = 3.14159…
-
math.prod(iter)
-
Return the product of the numbers in a list or other iterable.
-
math.sin(x)
-
Return the sine of x
in radians.
-
math.sqrt(x)
-
Return the square
root of x.
-
math.tan(x)
-
Return the tangent of x in radians.
-
math.tau
-
The constant τ = 2π = 6.283185…
import os
-
- In the methods below, path
is a string representing a filename, possibly with one or more
leading directory components. For example, path
could be
-
'abc.txt'
-
'photos/image.png' (a path that
is relative
to the current working directory)
-
'/home/natasha/documents/essay.txt'
(an absolute path)
-
- os.listdir(path)
-
Return a list of all filenames in the directory given by path.
-
os.makedirs(path, *, exist_ok = False)
-
Create a directory (including
any parent directories as necessary). If exist_ok is True, no error
is raised if the directory already exists.
-
os.remove(path)
-
Delete a file.
-
os.path.basename(path)
-
Return the base name of the given path. For example, the base name
of '/foo/bar/xyz.txt' is 'xyz.txt'.
-
os.path.dirname(path)
-
Return the directory name of the given path. For example, the
directory name of '/foo/bar/xyz.txt' is '/foo/bar'.
-
os.path.exists(path)
-
Return true if path is an
existing file or directory.
-
os.path.isdir(path)
-
Return true if path exists and is a directory.
-
os.path.isfile(path)
-
Return true if path exists
and is a regular file.
-
os.path.join(*paths)
-
Join one or more paths, inserting
directory separator characters ('/' or '\') between
path components.
-
os.system(command)
-
Execute a shell command. You can use this function to run an
external program.
import random
This module generates pseudo-random numbers.
-
- random.choice(seq)
-
Return a random element from a non-empty sequence.
-
random.randint(a, b)
-
Return a random integer n in the range a ≤ n ≤ b.
-
random.random()
-
Return a random float x in the range 0.0 ≤ x < 1.0.
-
random.randrange([a],
b)
-
Return a random integer n in the range a
≤ n < b. a
defaults to 0.
-
random.seed(a)
-
Seed the random number generator with an integer value. If you use
the same seed in two runs of your program, you'll get the same
random number sequence.
-
random.uniform(a, b)
-
Return a random float x in the range a ≤ x ≤ b.
import re
-
- This module implements
regular expressions. Here is a summary
of regular expression syntax.
functions
-
- re.findall(pattern, string)
-
Return a list of strings representing all non-overlapping matches of
pattern in string,
in left-to-right order. If pattern
contains two or more groups, each list element is actually a tuple
of strings.
-
re.finditer(pattern, string)
-
Return an iterable of match objects representing all matches of
pattern in string.
-
re.fullmatch(pattern, string)
-
If the entire string matches the regular expression pattern,
return a match object representing the match; otherwise return None.
-
re.match(pattern, string)
-
If the beginning of the string matches the regular expression
pattern, return a match object representing the match;
otherwise return None.
-
re.search(pattern, string)
-
If the string contains a match for the regular expression pattern,
return a match object representing the first such match. If there is
no match, return None.
-
re.sub(pattern, replacement, string)
-
Return a string generated by replacing all occurrences of pattern
in string with replacement.
match objects
A match object represents a match of a regular expression
at a particular position in a string. In a boolean context, a match
object is always True.
-
- m[number]
-
If number
is 0, return the entire
text that matched. If number
> 0, return
the string matching the corresponding parenthesized group.
-
m.groups()
-
Return a tuple containing the strings that matched each group in the
pattern.
import sys
-
- sys.argv
-
A program's command-line arguments. sys.argv[0] is the name of the
program itself, and the following elements are the actual arguments.
-
sys.exit()
-
Exit the program immediately.
-
sys.stdin
-
The program's standard input. This is an iterable object
representing a series
of lines of text. Each line will end with a newline character
('\n').
import time
-
- time.sleep(secs)
-
Wait for the given number of seconds, which may be a floating-point
number.
-
time.time()
-
Return a float representing the number of seconds elapsed since
January 1, 1970.
import
matplotlib.pyplot as plt
Matplotlib is a library for
visualizing data. To install it, run
$ pip install matplotlib
-
-
plt.bar(xs, ys)
-
Plot data as a series of vertical bars.
-
plt.barh(xs, ys)
-
Plot data as a series of horizontal bars.
-
plt.figure(*, figsize = (x, y))
-
Create a new figure (i.e. a graph). x and y specify its width and
height in inches.
-
plt.grid(*, axis = 'both')
-
Enable grid lines on a plot. The axis parameter indicates the
axis on which to draw grid lines, and may be 'x', 'y', or 'both'.
-
plt.legend()
-
Display a legend, which shows labels for each plot on the graph.
-
plt.plot(xs, ys, symbol = '-', *, label = string)
-
Plot data. xs contains a series of numeric x-values, and ys contains
a corresponding series of y-values. 'symbol' is a marker for
plotting points, such as 'o', 'x', or '+'; if omitted, a line plot
is drawn. You may specify a label for the plot.
-
plt.savefig(filename)
-
Save the current plot to the given file. The filename's extension
determines the format in which to save. For example, 'my_plot.svg'
will be saved in SVG format.
-
plt.show()
-
Display the current graph.
-
plt.title(string)
-
Set a title for the graph.
-
plt.xlabel(string)
-
Set a label for the x-axis.
-
plt.xlim(lo, hi)
-
Specify low and high values for the x-axis.
-
plt.ylabel(string)
-
Set a label for the y-axis.
-
plt.ylim(lo, hi)
-
Specify low and high values for the y-axis.