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 creationsimport array as arr# to create an array of integer datatype ia = arr.array('i', [1, 2, 3, 4, 5, 6, 7 ])# printing the newly created arrayprint('The integer datatype of array is: ', a)# to check for the type of arrayprint("The data type of the array is: ", a.typecode)
Explanation
- Line 2: We import the
arraymodule in Python. - Line 5: We create an array variable
aof integer type. - Line 8: We print the array variable
a, which we created in line 5. - Line 11: We use the
array.typecodefunction to check the data type of the array we created.
Creating an array with the double float 'd' data type
# importing array from array creationsimport array as arr# to create an arry in double float datatype da =arr.array('d', [1.2, 2.5, 6.4, 5.1, 4.5] )# printing the float arrayprint('The float datatype of array is: ', a)# to check for the data type of the arrayprint("The data type of the array is: ", a.typecode)
Explanation
- Line 2: We import the
arraymodule in Python. - Line 5: We create an array variable
aof float data type. - Line 8: We print the array variable
a, which we created in line 5. - Line 11: Using the
array.typecodefunction, we check for the data type of the array we created.