Dynamic Arrays in Python Using Numpy
By Hans Tercek on 2/15/2018
Edit 2/19/18: The EV3 bricks do not appear to come with Numpy pre-installed. If working with the EV3, stick to Python's lists. If running Python on a Linux machine or on macOS, run the following command from your terminal to install Numpy:
Python 2.:
>> pip install numpy
Python 3.:
>> pip3 install numpy
Fun fact: Python's built in "array" system (i.e. declaring x = [1, 2, 3]) is not actually declaring x to be an array of integers. Instead, Python uses lists.
While lists operate, by-and-large, very similarly to traditional arrays, they are stored and accessed in a manner that is much less efficient than traditional arrays and they can be quite tricky to perform mathematic operations on (try multiplying a list and see what outputs).
Enter... Numpy
Numpy is a great mathematical toolkit for Python that also happens to include a phenomenal array feature. It serves as the foundation on which most matrix-heavy Python packages are built (take OpenCV for example... because images are a 2D array of integer values, OpenCV uses Numpy for its array features).
Using Numpy is super easy to use. Just as you'd import any package in Python, at the top of your file, include the following line:
| >> import numpy as np
This allows you to reference any feature in Numpy by typing "np"
Now, let's use Numpy's array feature.
Full documentation can be found here, but I'll write a quick guide to serve as a brief intro:
To create an array, simply initialize a variable as an empty array. The default type for arrays is float64 (64 bit floating point). You can specify datatype if memory constraints are an issue.
| >> x = np.array([1, 2, 3])
| >> print(x)
| [1, 2, 3]
To append elements to an array:
| >> x = np.append(x, 1)
| >> print(x)
| [1, 2, 3, 1]
To index an array:
| >> x2| 3
To delete elements from an array:
| >> x = np.delete(x, [2, 3])
| >> print(x)
To perform a mathematical operation on each element of an array:
| >> x = x 2
| >> print(x)
| [2, 4]
While most material for the class can be handled using Python's built-in lists, Numpy arrays are a handy tool to know. They are considered a Python standard, are applied heavily in third party packages, and can be quite handy for writing your own code. Give them a shot in your own projects!