If you come from C++, C#, or Java background, we all know arrays are a separate data type, but in Python most we hear is we can make use of a list for arrays. But do you know there is an array module that you can make use of specifically to create array types.
Using the array's module we can create a more memory-efficient array type that allows us to store elements of the same data type.
Example 1: Array of Integers
import array
int_array = array.array('i', [1, 2, 3, 4, 5])
print(int_array)
Example 2: Array of floats
import array
int_array = array.array('f', [1.5, 2.5, 3.9, 4, 50.1])
print(int_array)
List of types in Python Arrays
| Type code | C Type | Python Type | Minimum size in bytes |
|---|---|---|---|
| 'b' | signed char | int | 1 |
| 'B' | unsigned char | int | 1 |
| 'u' | wchar_t | str | 2 |
| 'h' | signed short | int | 2 |
| 'H' | unsigned short | int | 2 |
| 'i' | signed int | int | 2 |
| 'I' | unsigned int | int | 2 |
| 'l' | signed long | int | 4 |
| 'L' | unsigned long | int | 4 |
| 'q' | signed long long | int | 8 |
| 'Q' | unsigned long long | int | 8 |
| 'f' | float | float | 4 |
| 'd' | double | float | 8 |
Reference: https://docs.python.org/3/library/array.html#module-array
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!