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 include i for signed integer, f for float, and b for 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 as typecode. This parameter is also mandatory.

Let’s take a look at the following example to have better understanding.

Code example

#import module
from array import array
#initialize array with integer values
array_one = array("i", [1, 2, 3, 4, 5])
print(array_one)
#initialize array with double values
array_two = array("d", [6.4, 2.2, 8.7])
print(array_two)
#initialize array with float values
array_three = array("f", [5.72, 7.48, 0.43])
print(array_three)
#initialize array with signed values
array_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 integer values.

  • Line 9: We initialize an array with double values.

  • Line 13: We initialize an array with float values.

  • Line 17: We initialize an array with signed values.

  • Line 18: We print all the arrays.

Free Resources