Python Cheat Sheet

I've been using Python after a dry spell of using other languages. I went through the basic mechanics of the language and tried to use a wide variety of different techniques to cover most of the usage. Here's what I came up with.

from random import random, randint, choice, shuffle
from math import log, log10, log2
from itertools import count, repeat, cycle, chain, islice
import re


print('lists')
l = [1, 2, 4, 3, 5]
print(l)
l.append(6)
l.extend([8, 7])
print(l)
print(sorted(l, reverse=True))
print(reversed(l))
for i, x in enumerate(l):
    print(i, x)
print()

print('dicts')
d = {'a': 1, 'b': 2, 'c': 3}
print(d, d.keys(), d.values())
print(d.get('a'), d['b'], d.get('z'))
d.setdefault(0)
print(d.get('z'))
d.update({'d': 4})
print(d)
print(dict(zip(range(9), l)))
print()

print('sets')
s = set([1, 1, 1, 2])
s.add(3)
s.remove(3)
s.discard(55)
print(s, s.union([4]))
print(s.difference([1]))
print(s.intersection([1]))
print()

print('regex')
m = re.search(r'(\d{4})-(\d{2})-(\d{2})', '2016-01-01')
print(m.groups())
res = "1a2b3c"
newres = re.sub(r'[a-z]', ' ', res)
print(newres)
print()

print('itertools')
print(list(islice(count(start=0, step=1), 2)))
print(list(repeat(5, 3)))
print(list(chain([1, 2, 3], [4, 5, 6])))
print(list(islice(cycle([1, 2, 3]), 7)))


def count2(start, step):
    while True:
        yield start
        start += step


print(next(count2(6, 2)))
print()

print('type')
print(type(5), isinstance(5, int))
print()

print('string')
s = ' asdf,abc#'
print(s.strip(), s.strip('#'))
print(s.split(','), ','.join(str(x) for x in [1, 2, 3]))
print(s.find(','), s.find('x'))
print('{}: ${:3,}'.format('Cost', 1234))
print()

print('stdin')
# if __name__ == '__main__':
# jptr = open(os.environ['OUTPUT_PATH'], 'w')
# s = input()
# result = isValid(s)
# fptr.write(result + '\n')
# fptr.close()
print()

print('numbers')
s = '123'
i = int(s)
print(pow(i, 2), abs(-i), round(i + .94423, 3))
print(log2(i))
r_float = random()
r_int = randint(0, 10)
arr = [1, 2, 3]
r_el = choice(arr)
shuffle(arr)
print(r_float, r_int, arr, r_el)
print(~100, 101 & 9, 101 | 9)
print()

print('date')
from datetime import date, time, datetime, timedelta
now = datetime.utcnow()
print(now)
print()

print('list comprehension')
l = [i+1 for i in range(5)]                   # [1, 2, ..., 10]
s  = {i for i in range(10) if i >3}            # {6, 7, 8, 9}
iter = (i+5 for i in range(5))                   # (5, 6, ..., 14)
d = {i: i*2 for i in range(5)}                # {0: 0, 1: 2, ..., 9: 18}
from pprint import pprint
print(l, s, next(iter), d, any(x % 2 == 0 for x in iter))
pprint(d, width=10)
print()

print('lambda and enum')
from functools import reduce
iter = map(lambda x: x + 1, range(10))            # (1, 2, ..., 10)
iter2 = filter(lambda x: x > 5, range(10))         # (6, 7, 8, 9)
o  = reduce(lambda out, x: out + x, range(10))  # 45
print(next(iter), list(iter2), o)
from enum import Enum
Direction = Enum('Direction', 'n e s w')
print(Direction, Direction.n)
print()

print('try catch')
class CustomEx(Exception):
    pass

try:
    print('try')
    raise CustomEx('msg')
except CustomEx as e:
    print('except', e)
finally:
    print('finally')
print()