How to create an array with a defined data type in Python

Overview

With the help of type codes, we can dynamically create arrays of our own on Python. To recall what arrays are, see this link.

Creating an array with the integer 'i' data type

# importing array from array creations
import array as arr
# to create an array of integer datatype i
a = arr.array('i', [1, 2, 3, 4, 5, 6, 7 ])
# printing the newly created array
print('The integer datatype of array is: ', a)
# to check for the type of array
print("The data type of the array is: ", a.typecode)

Explanation

  • Line 2: We import the array module in Python.
  • Line 5: We create an array variable a of integer type.
  • Line 8: We print the array variable a, which we created in line 5.
  • Line 11: We use the array.typecode function to check the data type of the array we created.

Creating an array with the double float 'd' data type

# importing array from array creations
import array as arr
# to create an arry in double float datatype d
a =arr.array('d', [1.2, 2.5, 6.4, 5.1, 4.5] )
# printing the float array
print('The float datatype of array is: ', a)
# to check for the data type of the array
print("The data type of the array is: ", a.typecode)

Explanation

  • Line 2: We import the array module in Python.
  • Line 5: We create an array variable a of float data type.
  • Line 8: We print the array variable a, which we created in line 5.
  • Line 11: Using the array.typecode function, we check for the data type of the array we created.

Free Resources