You are on page 1of 3

Python Cheat Sheet: Built-in types, common functions, methods and packages Computer Sciences (07JCJ) — aa 2021/22 — Politecnico

ces (07JCJ) — aa 2021/22 — Politecnico di Torino

Common functions Strings


element (len(s)>=1), otherwise False.
print(x, x, x, ..., sep=’␣’, end=’\n’): sep int(s): converts s into an integer. Exception: s.isalpha(): returns True if s contains only alpha-
is the separator character between the values to be ValueError. betic characters ([a-zA-Z]) and has at least one
displayed (default is space), end is the terminating float(s): converts s into a float. Exception: element, otherwise False.
character (default is newline) ValueError. s.isdigit(): returns True if s contains only dig-
input(s): returns a string containing information str(x): converts x into string. its ([0-9]) and has at least one element, otherwise
entered from the keyboard (without ’\n’). ’s’ is ord(s): returns the Unicode point (an integer) of False.
the displayed message to the terminal. the character s (len(s) == 1). s.islower() / s.isupper(): returns True if s
range(i, j, k): generates a sequence of integers chr(i): returns the character (rune) that cor- contains only lowercase/uppercase ([a-z]/[A-Z])
starting from i (default i is 0), up to j (j is ex- responds to the Unicode point i. Exception: characters and has at least one element, otherwise
cluded from the sequence), with step k (default 1). ValueError. False.
s+s1: creates a new string by concatenating two ex- s.isspace(): returns True if s contains only
For most containers cont:
isting ones. whitespace characters i.e., spaces, tabs, newline
len(cont): returns the number of elements. s*n: creates a new string by concatenating n times ([’␣’,’\t’,’\n’]) and has at least one element,
x in cont: returns True if the element x is included the string s with itself. otherwise False.
in cont, False otherwise. s.lower() / s.upper(): returns the lowercase/up- From strings to lists and vice versa:
sum(cont): returns the sum of all values in cont. percase version of string s.
max(cont) / min(cont): returns the maxi- s.replace(s1, s2) / s.replace(s1, s2, n): re- s.split(sep, maxsplit=n): returns a list of sub-
mum/minimum value in cont. turns a copy of the string where each occurrence strings obtained by breaking s at each occurrence
cont.clear(): deletes all elements. of s1 in s have been substituted with s2. If n is of the string sep (separator). If sep if omitted, by
sorted(cont): returns a sorted list containing the provided, it replaces at most n occurrences of s1. default it breaks the string on spaces. If maxsplit
elements of cont (see note on section on sorting s.strip(s): returns a copy of s where leading is specified, at most n separations will be done,
complex data). and trailing whitespace characters (spaces, tabs, starting from the left (the final list will have at
newlines) have been removed. s.lstrip(s) / most n+1 elements).
For all sequences seq:
s.rstrip(s): do the same, but only for leading s.rsplit(sep, maxsplit=n): similar to split, but
seq.count(x): returns how many times x is present (left) or trailing (right) whitespace characters. the breaking of string s starts from the right.
in seq. s1 in s: returns True if s contains s1 as sub-string, s.splitlines(): similar to split, but uses as as
seq[i]: returns the element with the index i otherwise False. separator the newline ’\n’ and then divides s into
(i<len(seq), otherwise IndexError). If i<0, it s.count(s1): returns the number of occurrences of a list where each element is a line of text in s.
starts counting from the end of the seq. s1 in s. s.join(l): returns a single string containing all el-
seq[i:j]: returns a sub-sequence with consecutive s.startswith(s1) / s.endswith(s1): returns ements of l (which must be a list of strings) sepa-
elements from seq, starting from the element with True if s begins/ends with s1, otherwise False. rated by the separator s.
index i (default=0) and ending with the element s.find(s1) / s.find(s1, i, j): returns the first Formatted strings f’{x:fmt}’
with index j-1. (default=len(seq)). index of s when an occurrence of s1 begins, or -1
seq[i:j:k]: uses k as “step” to select the elements x is any variable or expression. fmt are format codes,
if not found. If i and j are present, searches for s1
of the new sub-sequence. If k<0 and i>j it starts which may contain:
in s[i:j].
counting from the end of the seq. < ^ >: for selecting left, center or right alignment
s.index(s1) / s.index(s1, i, j): similar to
,: to group digits with a comma (e.g., 1,234,567 )
find, but if s1 not found raises ValueError.
width: for indicating how many characters in to-
s.isalnum(): returns True if s contains only let-
tal the value must occupy. Default: the minimum
ters or digits ([a-zA-Z0-9]) and has at least one
File
number required. l + l1: returns a new list by concatenating the ele-
.precision: for indicating the number of decimal ments of l and l1. f = open(s, mode): opens the file named s. mode:
digits (if float) or maximum number of characters l == l1: returns True if the two lists contain ex- ’r’ reading, ’w’ writing. Returns a “file object”
(if not numeric). actly the same elements in the same order, other- f. Exceptions: FileNotFoundError if the file does
wise False. not exist, in general OSError.
Example: s string, d decimal integer, f real number, l.pop(): removes the last element from the list and f.close(): closes the (previously opened) file f.
g real number in scientific notation: returns it. with open(s,mode) as f: this statement wraps the
f"{n:5d}␣{a:7.2f}␣{s:>10s}" l.pop(i): removes the element at the position i and opening of the file named s with mode mode in a
returns it. The following elements are moved back block. It creates a “file object” f to be used within
Mathematics by one place. the block. When the code exits the with compound
l.insert(i, x): inserts x in the position i in list l. statement the file is automagically closed.
abs(a): |a| The following elements are moved forward by one f.readline(): returns a string of characters read
round(a), round(a, n): rounds a to the nearest in- place. from file f up to ’\n’ (including ’\n’). Returns
teger or to the float with n decimal digits if n is l.append(x): appends x at the end of the list l. "" (empty string) if at the end of the file.
specified. l.count(x): returns the number of occurrences of f.read(num): returns a string with (at most) num
floor(a)/ceil(a): ⌊a⌋ / ⌈a⌉ element x in list l characters read from the file f. If no argumnet is
trunc(a): eliminates the fractional part of a. l.index(x): returns the index of the first occur- used it returns the entire file as a single string.
rence of element x in the list l. If the element is f.readlines(): returns the file as a list of strings
import math ↘
not present in the list, it raises ValueError. as elements, where each string is a line of the file.
math.sin(a), cos(a), tan(a), exp(a), log(a), l.index(x, i, j): returns the index of the first oc- f.write(s): writes s to file f. Note: it does not
sqrt(a). They can raise ValueError. currence of the element x in the list l[i:j] (the el- automatically write a new line ’\n’.
math.isclose(a, b, rel_tol, abs_tol): returns ement in position j is not included in the search). print(..., file=f): similar to print, but writes
True if |a - b| is less or equal to rel_tol (relative The position is calculated from the beginning of to file f instead of the terminal.
tolerance) or abs_tol (absolute tolerance). the list. If not found, it raises ValueError. import csv ↘
l.remove(x): removes the element with the value x
import random ↘
from the list and move all elements that follow it csv.reader(f): returns a CSV reader object for the
random.random(): returns a random float number back by one place. If the element x is not in the file f to iterate over with a for loop, which yields
in the interval [0,1). list it raises ValueError. in each iteration a list whose elements are the fields
random.randint(i, j): returns a number integer l.extend(l1): extends the list l by appending to it of the next line of file f.
between i and j (j is included). all elements of list l1. csv.DictReader(f): returns a CSV dictionary
random.choice(seq): returns a randomly selected l.reverse(): changes the list l by reversing the or- reader object to iterate over with a for loop. The
element of seq. der of its elements. keys are the field names in the very first line of the
random.shuffle(seq): randomly shuffles the ele- l.copy() or list(l): returns a new list, which is a file, unless specified using option fieldnames=.
ments of seq. (shallow) copy of the list l. csv.writer(f): returns a CSV writer object
l.sort(reverse=False): Sorts in place the ele- for the file f opened for writing. Data
ments of the list. See the notes for sorted (see can be written line by line using either the
Lists
note on section on sorting complex data). method writerow(one_record) or the method
[]: creates and returns a new empty list. enumerate(l): returns a list of tuples of writerows(all_records).
[x, ..., x]: returns a new list with the supplied [(index1, value1), (index2, value2), ...], Option: use delimiter=’X’ to use ’X’ instead of the
elements. that allows you to iterate simultaneously on indices default comma ’,’ as a field separator. Useful for
list(cont): returns a new list containing all ele- and values of the list l. some Italian CSV that uses semicolon instead of
ments of container cont. comma.
l * n: returns a new list by replicating the elements Note: CSV files should be opened using option
of l exactly n times. newline=’’.
Sets Common Exceptions
key k, if present in d, otherwise it returns the de-
set(): returns a new empty set. fault value x. ValueError: incorrect argument value (e.g.,
set(cont): returns a new set that contains a copy d.pop(k): removes from d the key k and the value math.sqrt(-1)).
of cont (without duplicates). associated with it; if not present raises KeyError. IndexError: access to out-of-bound element in a se-
{x, x, ..., x}: returns a new set containing the Returns the deleted value. quence (e.g., l[len(l)]).
indicated elements (without duplicates). d.items(): returns a sequence of tuples KeyError: access to non-existing key in a collection
t.add(x): adds the new element x to set t. If the (key, value) of all elements of d, in order (e.g., dict()[’foo’]).
element already exists, nothing happens. of insertion. OSError: general exception for trapping I/O errors,
t.discard(x): removes the element x from set t. If d.values(): returns a sequence containing the val- such as FileNotFoundError, PermissionError,
the element is not in the set, nothing happens. ues of d. and FileExistsError.
t.remove(x): similar to discard, but if the element d.keys(): returns a sequence containing the keys of
is not in the set raises KeyError. d, in order of insertion. Legend (types of accepted arguments/objects)
t == t1: checks if the set t is equivalent with set sorted(d): returns a sorted list of the keys of the
t1. dictionary d (see note on section on sorting com- s, s1: string
t.issubset(t1) or t<=t1: checks if t ⊆ t1. plex data). a, b, c, ...: integer or float
t.issuperset(t1) or t>=t1: checks if t ⊇ t1. i, j, k, n: integer
t.isdisjoint(t1): returns True if the intersection x: any
of t and t1 is zero. import copy ↘ l, l1: list
t.union(t1) or t|t1: returns a new set equal to t d: dictionary
∪ t1. copy.copy(x): returns a shallow copy of x. It con- t, t1: set
t.intersection(t1) or t&t1: returns a new set structs a new object and then inserts into it refer- seq: sequence (list, tuple, string)
equal to t ∩ t1. ences to the objects found in the original (x). cont: container (list, tuple, string, set, dict)
t.difference(t1) or t-t1: returns a new set with copy.deepcopy(x): returns a deep copy of x. It con-
elements present in t but not in t1. structs a new object, then inserts a new replica of v0.5 @ 18/01/2022
t.symmetric_difference(t1) or t^t1: returns a the objects of the original container (x).
new set that contains elements that are present in
only one of the sets and not in both (operator x-or).
t.copy() or set(t): returns a (shallow) copy of the Sorting complex data
set t.
Optional parameters that can be used with sort,
Dictionaries sorted, max, and min. Note: itemgetter must be
imported as from operator import itemgetter.
dict() or {}: a new empty dictionary. reverse=True: reverse the comparison.
{k:x, ..., k:x}: a new dictionary containing the key=lambda key: data[key]: sort the dictionary
specified key/value pairs. data based on the value.
dict(d) or d.copy(): returns a shallow copy of the key=lambda elem: elem[’k’]: sort a list of
dictionary d. dictionaries based on the value of the en-
k in d: returns True if the key k exists in the dic- try with key k of each dictionary (alternative:
tionary d, otherwise False. key=itemgetter(’k’)).
d[k] = x: set the new key/value pair in the dictio- key=lambda elem: elem[n]: sort a list of lists, tu-
nary d. ples, or other sequences, based on their (n + 1)-th
d[k]: returns the value associated with the key k if value (alternative: key=itemgetter(n)).
present in d, otherwise raises KeyError.
d.get(k, x): returns the value associated with the

You might also like