← All lessons
Python advanced · Lesson 1 of 11

Before you start

This course follows Python intermediate. Here's what it assumes, in one place; if any line is new, the intermediate lesson on it is worth a look first.

  • A dict maps keys to values ({"a": 1}, d.get(k, default), d.items()); a set holds unique items; a tuple is an immutable sequence, and a, b = pair unpacks it.
  • A comprehension builds a list, dict or set in one expression: [x * 2 for x in xs if x > 0]. enumerate() numbers items and zip() pairs them.
  • Functions take default and keyword arguments, and *args / **kwargs collect extras. A name assigned inside a function is local to it.
  • try / except handles exceptions, raise signals one, and with makes sure a file (or anything else) is closed.
  • import loads a module; pip install adds a package.
  • A class is a blueprint for objects; __init__ sets up an instance, self is the instance, and methods with double underscores like __str__ are special methods Python calls itself.
from collections import Counter

class Tally:
    def __init__(self, words):
        self.counts = Counter(w.lower() for w in words)

    def __str__(self):
        top, n = self.counts.most_common(1)[0]
        return f"{top} x{n}"

print(Tally(["Duck", "goose", "duck"]))
Prints
duck x2

Practice

What does this print?

d = {"a": 1, "b": 2}
print({v: k for k, v in d.items()})
More info

Quick reference

dict / set / tupleKey-value map / unique items / immutable sequence.
comprehension[expr for x in xs if cond], and the dict and set forms.
try / except / raise / withHandle, signal and clean up after errors.
class / __init__ / selfBlueprint / set-up method / the instance.

Related courses