|
| 1 | +--- |
| 2 | +Title: 'size' |
| 3 | +Description: 'Returns the number of elements in a NumPy array.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Arrays' |
| 9 | + - 'Attributes' |
| 10 | + - 'NumPy' |
| 11 | + - 'Properties' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-python-3' |
| 14 | + - 'paths/computer-science' |
| 15 | +--- |
| 16 | + |
| 17 | +NumPy’s **`size`** attribute is used to find the total number of elements in an array. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +ndarray.size |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +`size` doesn’t take any parameters because it’s an attribute, not a method. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +Returns an integer representing the total number of elements in the array. |
| 32 | + |
| 33 | +## Example 1: Getting the Size of an Array Using `size` |
| 34 | + |
| 35 | +In this example, the code prints the total number of elements in the array: |
| 36 | + |
| 37 | +```py |
| 38 | +import numpy as np |
| 39 | + |
| 40 | +np_array = np.array([[1, 2, 3], [4, 5, 6]]) |
| 41 | +print(np_array.size) |
| 42 | +``` |
| 43 | + |
| 44 | +The output of this code is: |
| 45 | + |
| 46 | +```shell |
| 47 | +6 |
| 48 | +``` |
| 49 | + |
| 50 | +The array has 2 rows × 3 columns = 6 elements in total. |
| 51 | + |
| 52 | +## Example 2: Comparing `.shape` and `.size` |
| 53 | + |
| 54 | +In this example, `shape` displays the array’s dimensions, while `size` shows the total number of elements in the array: |
| 55 | + |
| 56 | +```py |
| 57 | +import numpy as np |
| 58 | + |
| 59 | +arr = np.array([[10, 20, 30], [40, 50, 60]]) |
| 60 | +print("Shape:", arr.shape) |
| 61 | +print("Size:", arr.size) |
| 62 | +``` |
| 63 | + |
| 64 | +The output of this code is: |
| 65 | + |
| 66 | +```shell |
| 67 | +Shape: (2, 3) |
| 68 | +Size: 6 |
| 69 | +``` |
| 70 | + |
| 71 | +`shape` returns the dimensions of the array, while `size` gives the total number of elements. |
| 72 | + |
| 73 | +## Codebyte Example: Using `.size` in a NumPy Operation |
| 74 | + |
| 75 | +In this example, `size` returns the total number of elements (12) in a reshaped 3×4 NumPy array: |
| 76 | + |
| 77 | +```codebyte/python |
| 78 | +import numpy as np |
| 79 | +
|
| 80 | +array = np.arange(12).reshape(3, 4) |
| 81 | +print("Array:") |
| 82 | +print(array) |
| 83 | +
|
| 84 | +print("Total elements:", array.size) |
| 85 | +``` |
0 commit comments