array¶
array
module offers a more specialized array data structure- The
array.array
class is designed to store a fixed-size collection of elements of the same data type. This can be useful for memory optimization when dealing with large amounts of numerical data, especially for primitive data types like integers or floats. - Unlike lists, arrays in the array module have a fixed size defined at creation and cannot be resized afterward.
- You need to specify a typecode to indicate the data type of the elements in the array. Here are some common typecodes:
- 'b': signed char
- 'B': unsigned char
- 'h': signed short
- 'H': unsigned short
- 'i': signed int
- 'I': unsigned int
- 'l': signed long
- 'L': unsigned long
- 'f': float
- 'd': double
- Accessing and Modifying Elements
- You can access elements by index using square brackets, similar to lists.
- However, modifying elements after creation is generally not recommended due to the fixed size nature of arrays. If you need to modify the data frequently, consider using lists or NumPy arrays.
- Common Array Methods
append(x)
: Not recommended as it's not efficient for fixed-size arrays.buffer_info()
: Returns a tuple of (address, length) of the underlying buffer used by the array.byteswap()
: Swaps the byte order of all the elements in the array (useful when working with different endianness systems).count(x)
: Counts the number of occurrences of the element x in the array.frombytes(s)
: Creates a new array from a string or byte buffer.fromfile(file, n)
: Reads n elements from a file-like object into the array.tolist()
: Returns a regular Python list containing copies of the array elements.tostring()
: Returns a string representation of the array's data.
- When to Use Arrays from the
array
Module- Use arrays from the
array
module when you need a memory-efficient way to store large collections of primitive numerical data types and don't require frequent modifications. - However, for more general-purpose data storage and manipulation, or when you need resizable arrays with various data types, consider using lists or NumPy arrays.
- Use arrays from the
- Additional Considerations
- The
array
module is a built-in module, but it's not as widely used as lists or NumPy arrays. - For most modern Python data science and numerical computing tasks, NumPy arrays are the preferred choice due to their rich functionality and performance optimizations.
- The
In [ ]:
Copied!
from array import array
# Array of integers
int_array = array('i', [1, 2, 3, 4])
# Array of floats
float_array = array('f', [1.5, 2.3, 4.1])
from array import array
# Array of integers
int_array = array('i', [1, 2, 3, 4])
# Array of floats
float_array = array('f', [1.5, 2.3, 4.1])