Functions often work on whole collections. How they behave depends on whether the collection is mutable. For numerical work, Python provides the math module and, as a separate library, NumPy.
Passing Collections to Functions
When a list, tuple or dictionary is passed to a function, the function receives a reference to the same object. If the object is mutable, changes made inside the function are visible outside, since both names refer to one object. A tuple cannot be changed, so the function can only read it. To protect a list, the function can work on a copy. A function can also return a list, tuple or dictionary, which allows several results to be sent back together.
The math Module
The math module gives mathematical functions after import math. Examples are math.sqrt(), math.pow(), math.floor(), math.ceil(), math.factorial(), math.gcd(), math.sin() and math.log(), and the constants math.pi and math.e. These functions work on single numbers, so to apply one to a list a loop or comprehension is used.
NumPy Arrays
NumPy is a library for fast numerical work. Its main object is the ndarray, an array of items of one type, created with numpy.array(), usually imported as np. An array differs from a list because arithmetic is applied to every element at once, so a 2 doubles each value. Useful functions are np.zeros(), np.ones(), np.arange(), np.linspace(), reshape(), and the summary functions sum(), mean(), max() and min(). The dot product of two arrays is np.dot(a, b). Operations that work on whole arrays without a loop are called vectorised*, and they are far faster than loops for large data.
Definition: NumPy array. A fixed-type, multi-dimensional array object (ndarray) that supports fast, element-wise arithmetic.
Table 3.3: List and NumPy array compared
| Feature | List | NumPy array |
|---|---|---|
| Items | Any types | One type |
| a * 2 | Repeats the list | Doubles each value |
| Speed | Slower | Much faster |
| Library | Built in | numpy |
Example 3.3: Function that changes a list, and NumPy operations
Problem: Write a function that doubles every item of a list in place. Then, for a = [1, 2, 3] and b = [4, 5, 6] as arrays, find the dot product, the maximum and a reshaped 2 by 3 array.
Solution:
- The function loops over the indices and assigns to each.
- Use np.dot(a, b), a.max() and np.arange(6).reshape(2, 3).
Result: The list is changed outside the function, and the dot product is 32.
import math
import numpy as np
def double(L):
for i in range(len(L)):
L[i] = L[i] * 2
data = [1, 2, 3]
double(data)
print(data)
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print(np.dot(a, b), a.max(), a * 2, np.ones(3))
print(np.arange(6).reshape(2, 3))
print(math.sqrt(16), math.factorial(5), round(math.pi, 4))
Output
[2, 4, 6]
32 3 [2 4 6] [1. 1. 1.]
[[0 1 2]
[3 4 5]]
4.0 120 3.1416
Common mistakes
- Importing numpy and forgetting the alias, then writing np without import numpy as np.
- Using + on lists and expecting element-wise addition. That joins them.
- Reshaping to a shape whose total size does not match the number of elements.
Key takeaways
- A mutable argument can be changed by the function.
- math gives single-number functions such as sqrt and factorial.
- NumPy arrays hold one type and support vectorised arithmetic.
- np.dot gives the dot product of two arrays.
Practice questions
- Can a function change a list passed to it?
- What does a * 2 give for a NumPy array a?
- Which function reshapes an array?
Answers to the practice questions
- Yes, because the list is mutable and the function receives a reference.
- An array with every element doubled.
- reshape().
Sources
- Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit III
