Python Quick Reference

For a more comprehensive guide on Python, we recommend this page. There is also a tutorial provided by the Python Software Foundation, found here.

Value Types

Python has what we call “weak typing” or “duck typing”: a variable’s type is determined by the value assigned to it, not declared explicitly when the variable is created.

Strings:

s = "foo bar"
s = 'foo bar'
s = """Hello
        World"""
example = "This is a string"
length = len(example)
f_string = f'The string "{example}" has the length of {length}'

Lists:

L = [1, 2, 3, 4, 5]
l = ['one', 2, 3.4, 'five']
L[0]                                  # single position
L[0:3]                                # the first three elements
L[-2:]                                # the last two elements
L[1:4] = [7,8]                        # substitute
del L[2]                              # remove elements
L.append(x)                           # x is a value
L.remove(x)
L.extend(L2)                          # or: L3 = L + L2
L.pop()                               # simple stack (with append)
L.sort()
x in L                                # does L contain x?
L.index(x)                            # index of the first occurrence
[x*2 for x in L if x>2]               # list comprehensions

Tuples:

x = 1,2,3
x = (1,2,3)
x[1]

Dictionaries:

D = {'f1': 10, 'f2': 20}              # dict creation
D = dict(f1=10, f2=20)

keys = ('a', 'b', 'c')
D = dict.fromkeys(keys)               # new dict with empty values
value = D['f1']                       # getting value out of a dictionary
value = D.get('f1', 'key not found')  # 'key not found' returned if f1 not found
dictionary = {
    'string': 'value',
    1: 'value',
    (1,2,3): 'tuple as a key'
}
for k in D: print(k)                  # keys
for v in D.values(): print(v)         # values
for k, v in D.items():                # tuples with keys and values
list(D.keys())                        # list of keys
sorted(D.keys())                      # sorted list of keys

D = {}

Looping

for x in range(6):                    # 0, 1, 2, 3, 4, 5
for x in range(1,6):                  # 1, 2, 3, 4, 5
for x in range(1,6,2):                # 1, 3, 5

for k,v in D.items():
    print(f"D[{k}]={v}")              # D[f1]=10  D[f2]=20

L = [1, 3, 5]
for i,v in enumerate(L):              # (index,value)
for x,y in zip(L1,L2):                # returns tuples
for i in sorted(set(L)): print(i)     # sorted set from a list
for x in reversed(L1):

Exceptions

try:
    raise TypeError("arg")
except (RuntimeError, NameError):
    pass                              # empty instruction (NOP)
except:
    info = sys.exc_info()
    print(info[0])
    print(info[1])
    traceback.print_tb(info[2])
    raise
else:
    ...                               # no exception but before finally
finally:                              # on the way out
    ...                               # unhandled exc, release resources

Magic Methods

Magic methods are special methods that can be added to classes. They are always surrounded by double underscores. A common magic method to add to a class is the __init__ method. This is a method that is called upon object initialization, used to define any parameters needed by the class.

from os.path import join

class FileObject:
    '''Wrapper for file objects to make sure the file gets closed on deletion.'''
    def __init__(self, filepath='~', filename='sample.txt'):
        # open a file filename in filepath in read and write mode
        self.file = open(join(filepath, filename), 'r+')

    def __del__(self):
        self.file.close()
        del self.file

Object-oriented programming

class Person:
    ID = 0                            # static variable
    def __init__(self, name, age=0):
        self.name = name
        self.age  = age
        Person.ID += 1
        self.ID = Person.ID
    def lastName(self):
        return self.name.split()[-1]
    def __str__(self):
        return f"{self.__class__.__name__}({self.name},{self.age})"

class Worker(Person):
    def __init__(self, name, position, age=0):
        super().__init__(name, age)
        self.position = position
    def __str__(self):
        return f"{self.__class__.__name__}({self.name},{self.position},{self.age})"
bob = Worker("Bob Smith", "developer", 25)
print(bob)