Historical post from January 4, 2023, corrected for the redesign. Versions and timings are examples from that time; check the current Python releases and your distribution's requirements.

Raspbian doesn't always ship with the Python version you want for a project. Here is a compressed example of how I built Python 3.11.1 on a Raspberry Pi. Python 3.11 was actually released on October 24, 2022, not in December.

Update packages

First update the package lists and installed packages:

sudo apt update
sudo apt upgrade

Dependencies

To compile Python we need build tools and development libraries:

sudo apt install -y libffi-dev libbz2-dev liblzma-dev \
    libsqlite3-dev libncurses5-dev libgdbm-dev zlib1g-dev \
    libreadline-dev libssl-dev tk-dev build-essential \
    libncursesw5-dev libc6-dev openssl git wget

Download the source

This example uses Python 3.11.1. Verify the download's integrity and signature against the information on python.org.

wget https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tar.gz
tar zxf Python-3.11.1.tar.gz
cd Python-3.11.1

Configure and build

Build the makefile. Optimizations can make the build considerably slower:

./configure --enable-optimizations
make -j 4 -l 4

On my Pi this took about half an hour to an hour back then. Your mileage will vary with the model and configuration. If the machine becomes unstable, reduce parallelism and check power, temperature and free space. Also check the build output for missing modules; usually a library is missing.

Test the built interpreter directly in the source directory:

./python -V

Install

To avoid overwriting the distribution's Python we use altinstall, not install. The chosen installation directory may require administrator privileges. This does not automatically make 3.11 the default python3; call it explicitly:

sudo make altinstall
python3.11 -V

The Python documentation recommends this too. Don't remove the development libraries blindly: other packages may still depend on them.