array

  • all of the members have to be of the same primitive type
  • the types supported are all numeric or other fixed-size primitive types such as bytes

Initialization

In [ ]:
from array import array

a = array('i', range(4)) # array('i', [0, 1, 2, 3])

# access element
print(type(a[1]), a[1]) # int 1

# slicing
b = a[:2] # array('i', [0, 1])
print(type(b)) # <class 'array.array'>

Methods

In [ ]:
a = array('i', range(4))

print(a.typecode) # check array type, i
print(a.itemsize) # the length in bytes of one array item

a.append(10) # array('i', [0, 1, 2, 3, 10])

a.extend(range(4)) # array('i', [0, 1, 2, 3, 10, 0, 1, 2, 3])

a.buffer_info() # give the current memory address and the length in elements of the buffer

a.count(2) # 2, return the number of occurrences of a specific item

a.index(3) # 3, return the index that a specific item first occur

a.insert(0, 100) # array('i', [100, 0, 1, 2, 3, 10, 0, 1, 2, 3])

a.pop(0) # array('i', [0, 1, 2, 3, 10, 0, 1, 2, 3]), remove and return a specific item, default index is -1

a.remove(1) # remove the first occurrence of x from the array

a.reverse() # array('i', [3, 2, 1, 0, 10, 3, 2, 0]), reverse the order of the items in the array

Built-in Functions

In [ ]:
a = array('i', range(4))

print(len(a)) # 4

l = list(a) # [0, 1, 2, 3], convert array to list
print(l)

s = sum(a) # 6