What is an array.array() in Python?
Overview
Python is a high-level programming language that provides functionalities for several operations. The array module comes with various methods to manipulate array data structures.
The function array.array() initializes an array with a typecode and initializer that must be a list, a bytes object, or an iterable.
Syntax
array.array(typecode[, initializer])
Arguments
typecode: The data type of the array is represented by single characters. Most commonly we includeifor signed integer,ffor float, andbfor signed characters. This parameter is mandatory.initializer: The initializer must be a bytes object, a list, or an iterable that has items of the same type astypecode. This parameter is also mandatory.
Let’s take a look at the following example to have better understanding.
Code example
#import modulefrom array import array#initialize array with integer valuesarray_one = array("i", [1, 2, 3, 4, 5])print(array_one)#initialize array with double valuesarray_two = array("d", [6.4, 2.2, 8.7])print(array_two)#initialize array with float valuesarray_three = array("f", [5.72, 7.48, 0.43])print(array_three)#initialize array with signed valuesarray_four = array("b", [-7, +8, -10, +14])print(array_four)
Explanation
-
Line 2: We import an array module.
-
Line 5: We initialize an array with
integervalues. -
Line 9: We initialize an array with
doublevalues. -
Line 13: We initialize an array with
floatvalues. -
Line 17: We initialize an array with
signedvalues. -
Line 18: We print all the arrays.