← Back to Python

All Topics

Advertisement

Learn/Python/Python Advanced

Array Module

Topic: Data Structures

Advertisement

Introduction

The array module provides space-efficient storage for homogeneous primitive types. It's more memory-efficient than lists for numeric data.

Basic Array

from array import array

# Create array of integers
numbers = array("i", [1, 2, 3, 4, 5])
print(numbers)        # array('i', [1, 2, 3, 4, 5])
print(numbers[0])     # 1
print(numbers[2:4])   # array('i', [3, 4])

# Array types: 'b' (signed char), 'B' (unsigned char),
# 'h' (short), 'H' (unsigned short), 'i' (int), 'I' (unsigned int),
# 'f' (float), 'd' (double)

Array Methods

from array import array

arr = array("i", [3, 1, 4, 1, 5])

arr.append(9)
arr.extend([2, 6])
arr.insert(0, 0)
arr.remove(1)  # Remove first occurrence
arr.pop()
arr.reverse()

print(list(arr))

Array from Bytes

from array import array

# Create from bytes
data = b"\x01\x02\x03\x04"
arr = array("B", data)
print(list(arr))  # [1, 2, 3, 4]

# Convert to bytes
back_to_bytes = arr.tobytes()
print(back_to_bytes)  # b'\x01\x02\x03\x04'

Type Codes

from array import array

# Numeric types
ints = array("i", [1, 2, 3])
floats = array("d", [1.1, 2.2, 3.3])

# Characters
chars = array("u", "Hello")  # Unicode
bytes_arr = array("b", b"Hello")  # Signed bytes

# Type info
print(array.typecodes)  # All available type codes

File I/O with Array

from array import array
import io

# Write to file
with open("data.bin", "wb") as f:
    arr = array("i", [1, 2, 3, 4, 5])
    arr.tofile(f)

# Read from file
with open("data.bin", "rb") as f:
    arr = array("i")
    arr.fromfile(f, 5)
    print(arr)

Practice Problems

  1. Create array with different type codes
  2. Use array methods (append, extend, remove)
  3. Convert between bytes and array
  4. Read/write array to file
  5. Compare array with list for memory

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →