Imagine you have two projects on your laptop: one needs version 1.0 of a library, and a newer one needs version 3.0 of the same library. If you install packages globally with pip, you can only have one version installed at a time — installing the newer one for project B silently breaks project A. A virtual environment solves this by giving each project its own isolated, self-contained set of installed packages.

Think of it as a clean, disposable copy of Python just for one project, completely separate from your system's main Python installation and from every other project's environment.

Creating a Virtual Environment

Python includes the venv module for this out of the box — no separate installation needed:

python -m venv env

This creates a folder named env in your project directory containing a private copy of the Python interpreter and an empty site-packages folder, ready for its own dependencies. You can name the folder anything — env, venv, and .venv are all common conventions.

Activating It

Creating the environment isn't enough — you have to activate it so your terminal starts using it instead of the system Python:

# Windows
env\Scripts\activate

# macOS / Linux
source env/bin/activate

Once activated, your terminal prompt usually changes to show the environment name, like (env) C:\myproject>. From this point on, any pip install you run only affects this environment — it never touches your global Python installation or any other project.

Installing Packages Inside It

pip install requests
pip list

Output:

Package    Version
---------- -------
pip        24.0
requests  2.31.0

Notice how short that list is — a fresh virtual environment starts with almost nothing installed, unlike your system Python which may have dozens of packages from unrelated projects accumulated over time.

Deactivating

deactivate

This single command returns your terminal to the system Python. You can reactivate the same environment any time by running the activation command again — nothing installed inside it is lost.

Typical Workflow

A standard project setup looks like this: create the environment once, activate it, install dependencies, then save them to a requirements.txt file so anyone else cloning the project can recreate the exact same environment:

python -m venv env
source env/bin/activate
pip install requests flask
pip freeze > requirements.txt

One more thing worth knowing: the env folder should never be committed to version control. It's typically added to .gitignore, since it's large, machine-specific, and fully reproducible from requirements.txt alone.