DEV Community

cloudytech147
cloudytech147

Posted on

Python Arrays

There is a problem with lists, its violets are the basic property of an array which is a homogeneous collection of elements.

Though there is no in-built support for arrays in python, we can use a module name array to create an array data structure.

Python Arrays

Image credits to analyticsvidhya

Syntax to create an array in Python using array Module:

import array

variable_name = array.array('Type code',[item1 , item2, item3,])
Enter fullscreen mode Exit fullscreen mode

Example:

import array

arr = array.array('d', [1,2,3,4])
Enter fullscreen mode Exit fullscreen mode

Arrays in Python Type codes:

The Unicode decide the data type of all the elements and all the element data type should match the type code.

Syntax:

array.array(‘Type code or UniCode’ , [list of items] )
Enter fullscreen mode Exit fullscreen mode

Syntax

With the array module, we can only create an array of numeric elements.

In general, we use python lists as arrays, but theoretically, arrays cannot store different data types at once.

Python List

python_list = [1,2,3,4,5,"This is a List"]
print(python_list)
Enter fullscreen mode Exit fullscreen mode

Array Module in Python

import array

python_array = array.array('i' , [1,2,4,5,6,7,])
print(python_array)
Enter fullscreen mode Exit fullscreen mode

Conclusion:

We do not use a python array module to build arrays because we cannot perform a mathematical or arithmetic operation on array elements.

Top comments (0)