The Array in Python

Array

A one-dimensional array is a collection of contiguous elements in which individual elements are identified by a unique integer subscript starting with zero. Once an array is created, its size cannot be changed.

  • Array( size ): Creates a one-dimensional array consisting of size elements with each element initially set to None. size must be greater than zero.
  • length (): Returns the length or number of elements in the array.
  • getitem ( index ): Returns the value stored in the array at element position index. The index argument must be within the valid range. Accessed using the subscript operator
  • setitem ( index, value ): Modifies the contents of the array element at position index to contain value. The index must be within the valid range. Accessed using the subscript operator
  • clearing( value ): Clears the array by setting every element to value.
  • iterator (): Creates and returns an iterator that can be used to traverse the elements of the array.

The Array in Python Example

# Fill a 1-D array with random values, then print them, one per line.
from array import Array
import random
# The constructor is called to create the array.
valueList = Array( 100 )
# Fill the array with random floating-point values.
for i in range( len( valueList ) ) :
valueList[ i ] = random.random()
# Print the values, one per line.
for value in valueList :
print( value )


Implementing the Array

Python is a scripting language built using the C language, a high-level language that requires a program’s source code be compiled into executable code before it can be used. The C language is a very powerful programming language that provides syntax for working with the complete functionality available by the underlying hardware. That syntax, however, can be somewhat cryptic compared to Python, especially for a Python programmer who may not be familiar with C

The ctypes Module

Many of the data types and classes available in Python are actually implemented using appropriate types from the C language. While Python does not provide the array structure as part of the language itself, it now includes the ctypes module as part of the Python Standard Library. This module provides access to the diverse set of data types available in the C language and the complete functionality provided by a wide range of C libraries.

The ctypes module provides the capability to create hardware-supported arrays just like the ones used to implement Python’s string, list, tuple, and dictionary collection types. But the ctypes module is not meant for everyday use in Python programs as it was designed for use by module developers to aide in creating more portable Python modules by bridging the gap between Python and the C language. Much of the functionality provided by the ctypes module requires some knowledge of the C language. Thus, the technique provided by the module for creating an array should not typically be used directly within a Python program. But we can use it within our Array class to provide the functionality defined by the Array ADT since the details will be hidden within the class.

Creating a Hardware Array

The ctypes module provides a technique for creating arrays that can store references to Python objects. The following code segment

import ctypes
ArrayType = ctypes.py_object * 5
slots = ArrayType()

creates an array named slots that contains five elements each of which can store a reference to an object. After the array has been created, the elements can be accessed using the same integer subscript notation as used with Python’s own sequence types. For the slots array, the legal range is [0 . . . 4].

The elements of the array have to be initialized before they can be used. If we attempt to read the contents of an element in the slots array before it has been initialized

print( slots[0] )

an exception would be raised in the same way as if we tried to print the value of a variable sum, that had not previously been assigned a value. Thus, the array should be initialized immediately after it has been created by assigning a value to each element using the subscript notation. Any value can be used, but a logical choice is to assign None to each element:

for i in range( 5 ) :
 slots[i] = None

Example of Array

1 # Implements the Array ADT using array capabilities of the ctypes module.
2 import ctypes
3
4 class Array :
5 # Creates an array with size elements.
6 def __init__( self, size ):
7 assert size > 0, "Array size must be > 0"
8 self._size = size
9 # Create the array structure using the ctypes module.
10 PyArrayType = ctypes.py_object * size
11 self._elements = PyArrayType()
12 # Initialize each element.
13 self.clear( None )
14
15 # Returns the size of the array.
16 def __len__( self ):
17 return self._size
18
19 # Gets the contents of the index element.
20 def __getitem__( self, index ):
21 assert index >= 0 and index < len(self), "Array subscript out of range"
22 return self._elements[ index ]
23
24 # Puts the value in the array element at index position.
25 def __setitem__( self, index, value ):
26 assert index >= 0 and index < len(self), "Array subscript out of range"
27 self._elements[ index ] = value
28
29 # Clears the array by setting each element to the given value.
30 def clear( self, value ):
31 for i in range( len(self) ) :
32 self._elements[i] = value
33
34 # Returns the array's iterator for traversing the elements.
35 def __iter__( self ):
36 return _ArrayIterator( self._elements )
37
38 # An iterator for the Array ADT.
39 class _ArrayIterator :
40 def __init__( self, theArray ):
41 self._arrayRef = theArray
42 self._curNdx = 0
43
44 def __iter__( self ):
45 return self
46
47 def __next__( self ):
48 if self._curNdx < len( self._arrayRef ) :
49 entry = self._arrayRef[ self._curNdx ]
50 self._curNdx += 1
51 return entry
52 else :
53 raise StopIteration


Leave a Comment