Arrays in Python
In Python, arrays can be implemented in multiple ways. The built-in list type is often used like an
array,
but Python also provides the array module for more memory-efficient storage of basic types. For
numerical and
scientific computing, the NumPy library offers powerful n-dimensional arrays.
1. Using Lists as Arrays
Lists in Python are dynamic and can hold elements of any type.
Example:
numbers = [1, 2, 3, 4, 5]
print(numbers[0]) # Output: 1
numbers.append(6)
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
2. The array Module
The array module provides arrays of a single data type.
Example:
import array as arr
a = arr.array('i', [1, 2, 3])
a.append(4)
print(a) # array('i', [1, 2, 3, 4])
Type Codes:
'i' - integer
'f' - float
'u' - Unicode character
3. NumPy Arrays
NumPy arrays are highly efficient for numerical work.
Example:
import numpy as np
a = np.array([1, 2, 3])
print(a + 10) # [11 12 13]
Features:
- Supports multi-dimensional arrays
- Broadcasting
- Vectorized operations
- Advanced indexing & slicing
4. When to Use What
- Use lists for general-purpose containers with mixed data types.
- Use array module for memory-efficient storage of uniform data.
- Use NumPy arrays for numerical/scientific computing and performance.