Python `array` Module

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.

Creating an array


    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:

  • 'b' - signed integer
  • 'B' - unsigned integer
  • 'u' - unsigned integer
  • 'h' - short integer
  • 'H' - unsigned short integer
  • 'i' - integer
  • 'I' - unsigned integer
  • 'l' - long integer
  • 'L' - unsigned long integer
  • 'q' - long long integer
  • 'Q' - unsigned long long integer
  • 'f' - float
  • 'd' - double-precision float

Accessing elements


    print(numbers[0])  # Output: 1
        

Appending elements


    numbers.append(6)
    print(numbers)  # Output: array('i', [1, 2, 3, 4, 5, 6])
        

Inserting elements


    numbers.insert(2, 10)  # Insert 10 at index 2
    print(numbers)
        

Output (example):


    array('i', [1, 2, 10, 3, 4, 5, 6])
    

Removing elements


    numbers.pop()  #Removes last element
    print(numbers)
    
    numbers.remove(10) #removes the first occurrence of 10
    print(numbers)
        

Iteration


    for num in numbers:
        print(num)
        

Checking type


    print(isinstance(numbers, array.array))  # Output: True
        

Important Note

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.