Skip to content
CodeNest

Applied PythonLesson 18 of 1913 min

The Standard Library

A tour of the batteries included: math, random, datetime, json, and collections.

By the end you will be able to

  • Reach for the standard library before writing it yourself
  • Work with dates, JSON, and random values
  • Use Counter and defaultdict to simplify tallying code

Python ships with a large standard library — no installation required. Knowing roughly what is in it is one of the highest-leverage things a beginner can learn, because the alternative is reinventing it badly.

Python
Output
9.0 2 3
3.1416 120
18
15.5
— expected output; press Run to execute it yourself

random produces different values on every run, so there is no fixed output to compare against — press Run a few times and watch it change. Calling random.seed(n) first makes a run reproducible, which is what you want in a test.

Python
Output

Press Run to execute this code.

Dates and times

Python
Output
2026-08-09
Sunday, 09 August 2026
2026 8 9
2026-09-23
45 days apart
2026-12-25
— expected output; press Run to execute it yourself

JSON

JSON is how programs exchange structured data. json.dumps turns Python objects into a JSON string; json.loads turns one back.

Python
Output
{
  "name": "Ada",
  "skills": [
    "Python",
    "maths"
  ],
  "active": true,
  "score": null
}
Python <class 'dict'>
— expected output; press Run to execute it yourself

collections

Counter and defaultdict replace whole blocks of hand-written tallying code.

Python
Output
Counter({'the': 3, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1, 'end': 1})
[('the', 3), ('cat', 1)]
3 0
{'t': ['the', 'the', 'the'], 'c': ['cat'], 's': ['sat'], 'o': ['on'], 'm': ['mat'], 'e': ['end']}
— expected output; press Run to execute it yourself

Exercise

Using collections.Counter, write most_common_word(text) that returns the single most frequent word in a sentence, lowercased.

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.What does json.loads(text) do?
  2. 2.What does Counter(['a','b','a'])['z'] return?