Create Python 3 Virtual Environment

Python is one of my favorite programming languages. I use it as part of my tutoring, datascience, serverless AWS Lambda Functions, and more.

When coding with Python it is best to create a virtual environment for your projects. Venv is built into Python 3 and creates a lightweight virtual environments for you projects.

Here is a quick example of using venv with Python 3.

Create a new directory for your project and switch into it.

$ mkdir my-project && cd my-project

Create a new virutal environment using venv. I have Python 2 and Python 3 installed on my MBP using Homebrew, so I reference Python 3 as python3. I am creating a new virtual environment called env.

$ python3 -m venv env

Activate the virtual environment.

$ source env\bin\activate
(env) $ 

Install any packages you wish. In this case I will install NumPy.

(env) $ pip install numpy
Collecting numpy ...

Now we can write some code using Python 3 and Numpy. I created a file.

import numpy as np

def main():
    np_array = np.array([1, 2, 3, 4, 5])
    print(f'The mean of {np_array} is {np.mean(np_array)}.')

if __name__ == "__main__":

Save the file and run it.

(env) $ python
The mean of [1 2 3 4 5] is 3.0.

When you’re done deactivate the virtual environment.

(env) $ deactivate