With Python and Python libraries such as NumPy, both methods and functions are used to perform operations on arrays.
A method, however, is a function that is attached to an object (in this case, a NumPy array object). It is called using the dot notation, i.e., array.method(). The method operates on the array that it is called on and usually returns a modified version of the same array. Some examples of NumPy array methods are ndarray.reshape(), ndarray.flatten(), and ndarray.sort().
Here’s an example of how to use the sort()
method on a NumPy ndarray
import numpy as np
# create a 2-dimensional ndarray
arr = np.array([[3, 2, 1], [6, 5, 4]])
# sort the ndarray along its last axis
arr.sort()
# print the sorted array
print(arr)
In this example, the sort() method is called on the arr ndarray. Since no axis is specified, the array is sorted along its last axis (which, in this case, is the second dimension). The resulting sorted array is then printed to the console.
Here’s what the output would look like:
[[1 2 3]
[4 5 6]]
As you can see, the sort()
method has rearranged the elements of arr
so that each row is now in ascending order.
In Python, a function is a named block of code that performs a specific task. It is a reusable piece of code that can be called multiple times from different parts of a program, making code more organized, readable, and easier to maintain.
A function in Python typically takes input arguments, performs some operations on them, and returns a result. The syntax for defining a function in Python is as follows:
def function_name(parameters):
# code block
return value
For example, here is a simple function that takes two numbers as input and returns their sum:
def add_numbers(x, y):
result = x + y
return result
sum = add_numbers(3, 5)
After executing this code, the variable sum
would contain the value 8
, which is the sum of the two input numbers.