python
  1. python-arrays

Python Arrays

Arrays in Python are used to store a collection of items of the same data type. An array can be of type integer, float or any other data type. Arrays in Python can be created by importing the array module.

Syntax

from array import array

arr = array(typecode, [initializer])

Here, typecode is the data type of the array. The available type code identifiers can be found on the official Python documentation. The initializer is an optional list of values to initialize the array.

Example

from array import array

arr = array('i', [1, 2, 3, 4, 5])
print(arr)

Output:

array('i', [1, 2, 3, 4, 5])

Explanation

In the above example, we imported the array module and created an array named arr with typecode 'i' (integer) and initialized with values [1, 2, 3, 4, 5].

Use

Arrays are useful when we need a collection of items of the same data type. They are especially useful when we need to perform operations on all items of the collection.

Important Points

  • Arrays can only store one data type.
  • Arrays are mutable. We can change the value of elements in an array.
  • Arrays support all normal sequence operations like slicing, concatenation, etc.
  • Arrays are generally faster than lists for bulk data operations.

Summary

Arrays in Python are useful for storing a collection of items of the same data type. They are faster than lists for bulk data operations and support all normal sequence operations. Arrays can only store one data type and are mutable.

Published on: