The `array` module in Python provides an efficient way to work with numerical arrays. Unlike lists, arrays in this module are restricted to a single data type.
import array
# Create an array of integers
numbers = array.array('i', [1, 2, 3, 4, 5])
print(numbers)
Output (example):
array('i', [1, 2, 3, 4, 5])
The first argument ('i' in this case) specifies the data type. Valid type codes include:
print(numbers[0]) # Output: 1
numbers.append(6)
print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6])
numbers.insert(2, 10) # Insert 10 at index 2
print(numbers)
Output (example):
array('i', [1, 2, 10, 3, 4, 5, 6])
numbers.pop() #Removes last element
print(numbers)
numbers.remove(10) #removes the first occurrence of 10
print(numbers)
for num in numbers:
print(num)
print(isinstance(numbers, array.array)) # Output: True
Arrays in Python's `array` module are more memory-efficient than lists when storing homogeneous numerical data. But if you need more flexibility (i.e., storing different data types in a single list), a list is more appropriate. When using the `array` module, always ensure that all the elements you add to the array are of the same data type as specified during its creation.