Python Cheatsheet

kuniga.me > Docs > Python Cheatsheet

Python Cheatsheet

Syntax for common tasks I run into often. Assumes Python 3.

Collections

List

Map over list

xs = [1, 2, 3]
ys = [f(x) for x in xs]

Filter list

xs = [1, 2, 3]
ys = [x for x in xs if x % 2 == 0]

NOTE: filter and map can be combined into one.

Sort list

Using default sorting:

>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

Sorting using key function. For example, sort list of pairs by the second element:

sorted([[1, 3], [2, 2], [3, 1]], key=lambda x: x[1])

Sorting by custom comparator:

import functools

# Function that returns
# < 0 if a < b
# > 0 if a > b
# = 0 if a = b
def cmp(a, b):
    return a - b

sorted([3, 2, 1], key=functools.cmp_to_key(cmp))

Dictionaries

Map over dictionary

ys = {k: f(v) for k, v in xs.items()}

Sort dictionary

Dictionaries are unordered sets, so you likely want to work with a list after sorting.

d = {'a': 3, 'b': 2}
xs = sorted(d.items(), key=lambda x: x[1])

Sets

Create

s = {1, 2, 3}

Difference

s1 = set([1, 2])
s2 = set([2, 3])
s1 = s1 - s2 # {1}

Union

s1 = set([1, 2])
s2 = set([2, 3])
s1 = s1.union(s2) # {1, 2, 3}

Map over set

xs = {1, 2, 3}
ys = {f(x) for x in xs}

Object Oriented

Basic Syntax:

class C:
    def __init__(self, param):
        self.param

    def method(self):
        return self.param

    @staticmethod
    def static_method():
        return 1

Files

Read file

with open(filename, "r") as file:
    print(file.readlines())

Other Data Structures

Queue

The Queue class is an advanced implementation that can be used for example in multi-thread applications. We can still use it as a plain queue data structure.

from queue import Queue

# Create
q = Queue()

# Insert back
q.put(item)

# Retrieve and remove front
first = q.get()

# Front element without removing
first = q[0]

# Size
len(q)

# Is empty?
q.empty()