CIS 111 Arrays

Objectives

  • Import the proper module to use arrays
  • Create an array
  • Access elements of an array
  • Modify elements of an array

Array overview

  • array is not a built-in Python data type
  • import the array module to create and use arrays
  • constructor: array(dataType [, list of values])
  • arrays are ordered

Array data types

The following list shows Python array data type codes and their associated C data type counterparts.

  • 'b': signed char
  • 'B': unsigned char
  • 'h': signed short
  • 'H': unsigned short
  • 'i': signed int
  • 'I': unsigned int
  • 'l': signed long
  • 'L': unsigned long
  • 'q': signed long
  • 'Q': unsigned long
  • 'f': float
  • 'd': double

Array examples

from array import array ar = array('I', [5, 10, 15, 20]) # creates an array of unsigned integers print(len(ar)) # 4 print(ar) # array('I', [5, 10, 15, 20]) for i in ar: print(i, end=' ') # 5 10 15 20 ar.tolist() # returns a list version of the array ar.reverse() # reverses array print(ar) # array('I', [20, 15, 10, 5]) print(ar[1]) # 15 ar.append(20) # adds element to end of array print(ar) # array('I', [20, 15, 10, 5, 20]) print(ar.count(10)) # 1 (number of occurrences of value) print(ar.count(20)) # 2 (number of occurrences of value) print(ar.index(10)) # 2 (position of value in array) ar[0] = 3 # modifies first array element print(ar) # array('I', [3, 15, 10, 5, 20])