Install a different Python version in Ubuntu

by Felix Kinaro About 2 min reading time

Prerequisites

This guide has been tested on Ubuntu 18.04.5. It should work on recent versions as well.

  1. An Ubuntu 18.04 computer or virtual machine.
  2. A non-root user with sudo privileges.
  3. An internet connection to download source code.
  4. GNU Compiler collection installed

Procedure

Step 1: Install Ubuntu if you haven't already

Go to the Ubuntu downloads page and download your preferred version. I will not detail the entire installation process here.

New users can refer to the official guide.

Step 2: Create a non-root user account

Set up a non-root user account and grant sudo privilege. The first account created in Ubuntu is usually the default administrative account.

You can refer to this guide on Digitalocean

Step 3: Install GCC

Run sudo apt update && sudo apt-get install build-essential manpages

Verify that installation was successful: gcc --version

You should get output similar to this:

gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Step 4: Download Python source code

Get the source code.

We are going to work with version 3.9.0.
Choose the file with the .tar.xz extension
I am using wget to download it so in the Tremnal I will type wget https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tar.xz

Step 5: Extract the archive

  1. Run tar -xf Python-3.9.0.tar.xz
  2. cd to the Python directory: cd Python-3.9.0/

Step 6: Prepare for installation

  1. Check the number of CPU cores: nproc
  2. Configure with optimization: ./configure --enable-optimizations
  3. Specify the number of cores for the make command. This is the number returned by nproc. In my case it is 4, hence I run make -j 4

Step 7: Install

  1. Run sudo make altinstall to install Python 3.9.0
  2. Verify Installation: run python3.9 to open an interactive python console. You should get output like this:

Python 3.9.0 (default, May 21 2021, 07:36:43)

[GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>>

Conclusion

You should now be able to run the newly installed python version. The preinstalled version remains intact, so you do not break any system dependencies.

Follow me on Twitter @kinarokihara