NumPy is a Python module that allows for vectorized operations on arrays of data. For example, to add, say 1 to each of the elements of a list, say a list containing elements 1, 2, 3 (numbers or integers), you cannot simply write:

>>>numbers = [1, 2, 3]
>>>numbers + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list
>>>

(Concatenation is possible if you are adding another list. Also, if you want to add an element, you can use the function append or insert.)

One way to create a list out of this list where each element is incremented by one is by using a for loop or using a list comprehension.

Using a for loop

>>>numbers = [1, 2, 3]
>>>numbers2 = []
>>>for number in numbers:
...    numbers2.append(number + 1)
...
>>>print(numbers2)
[2, 3, 4]

Using a list comprehension

>>>numbers = [1, 2, 3]
>>>numbers3 = [x + 1 for x in numbers]
>>>print(numbers3)
[2, 3, 4]

But using the NumPy module, one can simply use the addition operation. But you need to first convert the list to a NumPy object.

>>>import numpy as np
>>>numbers = np.array([1, 2, 3])
>>>numbers + 1
array([2, 3, 4])

One game I was able to apply NumPy to is the game of tic-tac-toe. I modified this code which was an assignment for the EdX course, “Using Python for Research” taught by JP Onnela (I also highly recommend it). Here is the whole code, also on my GitHub gist. Among the NumPy operations I was able to use and really learn were:

  • numpy.where()
  • numpy.any()
  • numpy.all()

This game allows one to be able to choose whether you want to play the game, play first or second and play again.