Objectives
- Import the proper module to use arrays
- Create an array
- Access elements of an array
- Modify elements of an array
The following list shows Python array data type codes and their associated C data type counterparts.
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])