Some Python code samples which, similar to others here, are by no means exhaustive but just some things I wanted to write down.

Logic

True and False
True or False

Tuples

place = ("Sleat", 57.033527, -5.967830)
place[0]

for x in place:
    print(x)

place * 3
place + (3, "Sunshine")

foo = ("bar", ("baz", "qux"))
foo[1][0]

# 1-item tuple
t = (1,)

# empty tuple
e = ()

def minmax(items):
    return min(items), max(items)

min, max = minmax([34, 23, 65, 211, 93, 34, 2, 56, 234, 34, 10])

(a, (b, (c,))) = (1, (2, (3,)))
a, b = b, a

Strings

origin, _, destination = "London:Tokyo".partition(":")

# Concatenating
s1 = "Hello" + ", " + "World" + "!"

s2 = "Hello"
s2 += ", "
s2 += "World"
s2 += "!"

s3 = ''.join(["Hello", ", ", "World", "!"])

"Hello:, :World:!".split(":")

"Hello, {0}!".format("World")
"Hello, {}!".format("World")
"Hello, {to}!".format(to="World")

people = ("me", "you", "everybody")
"Hello from {p[0]} to {p[1]} and {p[2]}!".format(p=people)

import math
"Pi is {m.pi:.2f}".format(m=math)

# Byte strings
"こんにちは世界".encode('utf-8')
 b'\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\xaf\xe4\xb8\x96\xe7\x95\x8c'.decode('utf-8')  # Unicode codepoints

Ranges

stop = 10
for i in range(stop):
    print(i)

start = 4
for i in range(start, stop):
    print(i)

step = 2
for i in range(start, stop, step):
    print(i)

nums = list(range(10, 100, 7))
for num in nums:
     print(num)

items = [10, 17, 24, 31, 38, 45, 52, 59, 66, 73, 80, 87, 94]
for item in enumerate(items):
    print("The index is {idx} and the item is {itm}".format(idx=item[0], itm=item[1]))

for index, item in enumerate(items):
    print("The index is {idx} and the item is {itm}".format(idx=item, itm=item))

Lists

# Slicing
s = "Finally, as the sky began to grow light in the morning, I'd feel that I might be drifting off".split()
s[-2]  # second from end 'drifting'
s[1]  # second from beginning 'as'
s[2:8]  # third word until the eighth word ['the', 'sky', 'began', 'to', 'grow', 'light']
s[2:-11]  # third word until the twelfth from end ['as', 'the', 'sky', 'began', 'to', 'grow', 'light']
s[11:]  # Twelfth word until the end ["I'd", 'feel', 'that', 'I', 'might', 'be', 'drifting', 'off']
s[:7]  # The first seven words ['Finally,', 'as', 'the', 'sky', 'began', 'to', 'grow']
s2 = s[:]  # All words
s2 == s  # True
s2 is s  # False

# Containment
s.index('sky')
s.count('the')
'light' in s

# Removal
del s[1]
del s[s.index('light')]
# ...which is a verbose version of:
s.remove('drifting')

# Insertion
s.insert(6, 'brighter')

' '.join(s)

# Addition, new list:
s + ['so', 'there']
# Addition, modified in place:
s += ['so', 'there']
# AKA:
s.extend(['so', 'there'])

# Shallow list copy (same object references)
s2 = s[:]
s2 = s.copy()
s2 = list(s)  # Works with any iterable source, not just list

# Initialise a list of 100 zeroes
l = [0] * 100

# With a list of lists:
l = [[1, -1]] * 10
# Gives: [[1, -1], [1, -1], [1, -1], [1, -1], [1, -1], [1, -1], [1, -1], [1, -1], [1, -1], [1, -1]]
l[0].append[0]
# Gives:[[1, -1, 0], [1, -1, 0], [1, -1, 0], [1, -1, 0], [1, -1, 0], [1, -1, 0], [1, -1, 0], [1, -1, 0], [1, -1, 0], [1, -1, 0]]

# Reversing and Sorting, modified:
s.reverse()
s.sort()
s.sort(reverse=True)
s.sort(key=len)

# Sorting, unmodified:
s2 = sorted(s)
r = reversed(s)
list(r)

Dictonaries

d = {'key': 'value'}
d = dict([('key', 'value')])  # From list of tuples
d = dict(key='value')

d2 = d.copy()
d2 = dict(d)
d2.update(foo='bar')

# Iterate over keys
for key in d.keys():
    print("'{k}' -> '{v}'".format(k=key, v=d[key]))

# Or more concisely (as iterating over keys is default):
for key in d:
    print("'{k}' -> '{v}'".format(k=key, v=d[key]))

# Iterate over values
for value in d.values():
    print(value)

# Tuples from the .items() method
for key, value in d.items():
     
'key' in d  # True
'value' in d  # False

d = {'foo': 'bar', 'baz': 'qux'}
del d['baz']

d = {'foo': [0], 'bar': [0]}
d['foo'] += [1]  # {'foo': [0, 1], 'bar': [0]}
d['quux'] = [0]  # {'quux': [0], 'foo': [0, 1], 'bar': [0]}

# Pretty printing
from pprint import pprint as pp
pp(d)

Sets

s = {1, 2, 3, 1, 5, 2, 7, 2, 9}  # {1, 2, 3, 5, 7, 9}
7 in s  # True
7 not in s  # False
s.add(7)  # No effect if already present
s.update([0, 4, 6, 8])
s.remove(77)  # KeyError if not present
s.discard(77)  # No effect if not present
for x in s:
     print(x)

# Shallow copy
s2 = s.copy()
s2 = set(s)

# Set operations
flour = {'pancakes', 'pasta', 'batter'}
eggs = {'pasta', 'omelette', 'pancakes'}
milk = {'batter', 'omelette', 'pancakes'}
flour.union(eggs)
flour.union(eggs) == eggs.union(flour)  # Commutative
flour.intersection(eggs)
flour.intersection(eggs) == eggs.intersection(flour)  # Commutative
flour.difference(eggs)
flour.difference(eggs) == eggs.difference(flour)  # Not commutative
flour.symmetric_difference(eggs)
flour.difference(eggs)
flour.symmetric_difference(eggs) == eggs.symmetric_difference(flour)  # Commutative
favourite = {'pancakes'}
favourite.issubset(flour.union(eggs))
flour.union(eggs).issuperset(favourite)
dislike = {'gruel'}
favourite.isdisjoint(dislike)

# Empty set (as {} is an empty dictionary:
s = set()

Protocols

  • Container supports x in y and x not in y
  • Sized supports num = len(x)
  • Iterable supports iterator = iter(iterable)
  • Iterator supports item = next(iterator)
  • Sequence supports item = seq[index], index = seq.index(item), num = seq.count(item), and reversed(seq)
  • Mutable Sequence
  • Mutable Set
  • Mutable Mapping

Exception Handling

try:
    x = int("tiger")
except ValueError:
    print("Can't convert tigers to int!")
    x = int(-1)

try:
    x = int([1])
except (ValueError, TypeError) as e:
    x = int(-1)
    raise
finally:
    y = x

Comprehensions

# Imperative:
words = "Finally, as the sky began to grow light in the morning, I'd feel that I might be drifting off".split()
lengths = []
for word in words:
    lengths.append(len(word))

# Comprehension to create a list:
lengths = [len(word) for word in words]

# Comprehension to create a set:
lengths = {len(word) for word in words}

# Comprehension to create (flip) a dict:
en_to_fr = {'hello': 'bonjour', 'goodbye': 'au revoir'}
fr_to_en = {fr: en for en, fr in en_to_fr.items()}  # {'au revoir': 'goodbye', 'bonjour': 'hello'}

# Predicate filtering:
def is_longer_than(length, item):
    if len(item) > length:
        return True
    else:
        return False

long_lengths = [len(word) for word in words if is_longer_than(4, word)]

Iterators

words = "Finally, as the sky began to grow light in the morning, I'd feel that I might be drifting off".split()
iterator = iter(words)
try:
    next(iterator)
except StopIteration:
    pass

Generators

def generate_message():
    yield "Hello"
    yield "World"

for word in generate_message():
    print(word)

# Stateful generator
def generate_distinct(items):
    used = set()
    for item in items:
        if item in used:
            continue
        yield item
        used.add(item)

distinct_items = generate_distinct([1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 4, 4, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9, 9, 0])
for distinct_item in distinct_items:
    print(distinct_item)

# Lazy evaluation with comprehension
one_million_numbers = (x + 1 for x in range(1, 1000001))
next(million)

sum((x * x for x in range(1, 1001)))

# (Using [check-if-a-number-is-a-prime-number-python](https://www.daniweb.com/programming/software-development/code/216880/check-if-a-number-is-a-prime-number-python)
sum(x for x in range(1, 1001) if isprime(x))

Itertools

from itertools import islice, count
thousand_primes = sum(islice((x for x in count() if isprime(x)), 1000))

# Any (are true)
any(isprime(x) for x in range(1, 1000))

# All (are True)
long_words = "exponential infinitesimal existential paradigm".split()
all(len(word) > 7 for word in long_words)

# Zip
list_a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
list_b = [0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
for a, b in zip(list_a, list_b):
    print("{} - {}".format(a, b))

# Chain 
c = chain(list_a, list_b)
for a in c:
    print("{}".format(a))

Classes

class Foo:
    pass

class Bar:
    def baz(self):
        return "qux"

b = Bar()
b.baz()  # Which is syntactic sugar for the uncommon `Foo.bar(f)`


class Foo:
    def __init__(self, bar):
        if not bar.isalpha():
            raise ValueError("{} is not alphanumeric".format(bar))
        self._bar = bar

    def baz(self):
        return self._bar

from foo import Foo
f = Foo("@")  # Fails with ValueError
f = Foo("baz")
f.bar()  # returns `"baz"`

# Inheritance
class Bar:
    def baz(self):
        return self._bar

class Foo(Bar):
    def __init__(self, bar):
        if not bar.isalpha():
            raise ValueError("{} is not alphanumeric".format(bar))
        self._bar = bar

Using Files

f = open('message.txt', mode='wt', encoding='utf-8')
f.write('The message is...\n')
f.write('Hello, World!')
f.close()

g = open('message.txt', mode='rt', encoding='utf-8')
g.read()
g.seek(0)
g.readline()
g.seek(0)
g.readlines()
f.close()

h = open('message.txt', mode='at', encoding='utf-8')
h.writelines(["\n...and ever more shall be so..."])
h.close()

import sys
file = open('message.txt', mode='rt', encoding='utf-8')
for line in file:
    sys.stdout.write(line)  # Prints without extra new lines
file.close()

# Using with-block syntactic sugar
with open('message.txt', mode='rt', encoding='utf-8') as f:
    [len(line.strip()) for line in f]

Bitwise operations

x = bin(481)  # '0b111100001'
y = bin(256)  # '0b100000000'

a = int(x, 2)
b = int(y, 2)

c = a & b  # bitwise '0b111100001' and '0b100000000' leaving MSB
d = a | b  # bitwise '0b111100001' or '0b100000000' leaving  '0b111100001'
e = a ^ b  # bitwise '0b111100001' not '0b100000000' leaving '0b011100001'

f = b >> 1  # shift '0b100000000' (256 dec) 1 bit to '0b010000000' (128 dec)
g = b << 1  # shift '0b100000000' (256 dec) 1 bit to '0b1000000000' (512 dec)
1 << 0x1a  # 1 shifted right by 26 dec to 67108864

h = bin(e)  # '0b11100001'
i = int(h, 2)  # 255

Bytes

b = bytes(b'1234')
x = b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24)  # bytes to int32

Reading from a file by URL with ‘closing’ context manager

import re
import sys
from contextlib import closing
from urllib.request import urlopen
from collections import Counter


try:
    num_uncommon = int(sys.argv[1])
except ValueError:
    print('Unknown number \'{}\', using 5'.format(sys.argv[1]))
    num_uncommon = 5

with closing(urlopen('http://andr.io/t/sleep.txt')) as page:
    story = re.sub('[^A-Za-z ]+', ' ', page.read().decode('utf-8'))
    words = Counter(story.split())

uncommon = words.most_common()[:-num_uncommon-1:-1]
print('{} uncommon words are; {}'.format(num_uncommon, ', '.join([word[0].lower() for word in uncommon])))

Unittest

import unittest


def bar(baz):
    return "bar: {}".format(baz)


class TestFoo(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_bar_runs(self):
        bar("baz")

    def test_baz_value(self):
        self.assertEqual(bar("baz"), "bar: baz")


if __name__ == "__main__":
    unittest.main()

Python Debugger

import pdb
pdb.set_trace()
python3 -m pdb foo.py

Distutils

from distutils.core import setup

setup(
	name='foo',
	version='1.0',
	py_modules=['foo'],
	
	author='A Coder',
	author_email='a.coder@example.com',
	description='Foo bar baz',
	licence='MIT License',
	keywords='qux'
)

Current time in milliseconds

import time
current_time_millis = lambda: int(round(time.time() * 1000))