Python
Library Quick Reference
This page describes the
subset of the Python library that we have learned 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:
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.)
-
max(iter, [key =
f])
max(arg1, arg2, …, [key = f]) -
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.
-
min(iter, [key = f])
min(arg1, arg2, …, [key = f]) -
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.
-
sorted(iter, [key = f])
-
Return a new sorted list of the items in iter. 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.
sequences
Sequences include lists, 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.
-
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.index(x)
-
Return the index of the first occurrence of x in s. If x is not in
s, this raises a
ValueError
. -
s.reverse()
-
Reverse the elements of a sequence in place.
-
Comparison operators such
as ==, < and > also work on sequences. Operators such as <
and > 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].
-
del l[i : j : k]
-
Delete
a slice of elements from l[i] up
to (but not including)
l[j], stepping by k.
-
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.sort(key = None)
-
Sort a list in place. 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.isalnum()
-
True if all characters in s are letters or digits (and there is at
least one character).
-
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.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.
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.
input
and output
- close(file)
-
Call this function 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.
-
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.
-
print(*objects, end
= '\n', file = sys.stdout)
-
Print one or more objects. 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.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.deque()
-
Create a deque, i.e. a double-ended queue. 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 math
- math.ceil(x)
-
Return x rounded up to the nearest integer.
-
math.cos(x)
-
Return the cosine of x in radians.
-
math.e
-
The constant e = 2.71828…
-
math.floor(x)
-
Return x rounded down to the nearest integer.
-
math.inf
-
A floating-point number representing positive infinity.
-
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.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.
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.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.
import random
This module generates pseudo-random numbers.
- 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.uniform(a, b)
-
Return a random float x in the range a ≤ x ≤ b.
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.
import time
- time.time()
-
Return a float representing the number of seconds elapsed since
January 1, 1970.