Python notes

This post is inspired by post (in Russian) on
Habrahabr. Few things were not that apparent for already a few years of using Python, but can be very handy!

Accessing every second element:

Make a copy of list
y = x[:]

Create a deep copy (frequently asked on course):
import copy; copy.deepcopy()

Unpacking only first two parameters from a list:
first, second, *rest = list_expression

Getting default value for a key not present in a dictionary:
d[k] = d.get(k, 0) + 1
Compare this to

if k in d:
    d[k] += 1
    d[k] = 1

Dictionary comprehension:
{a:a**2 for a in range(1, 10)}