How To Declare Array In Python

In this tutorial, we will learn how to declare an array in Python. An array is an ordered collection of items that can store data of the same type.

In Python, you can use two main ways to declare an array: use the built-in list data structure or the array module. We will cover both methods in detail. Let’s get started!

Step 1: Declare an Array using the List

In Python, you can use the built-in list data structure to declare an array. Lists can store elements of different data types, but for the sake of creating an array, you should store elements of the same data type. To create a list, simply use square brackets [] and separate elements with a comma. Here’s an example:

To access elements of the list, use their index value, starting from 0.

To update an element in the list, use its index value and the assignment operator.

Step 2: Declare an Array using the Array Module

Python’s built-in array module provides an alternative way to declare an array. The array module creates an array with a specific data type, ensuring that all elements are of the same type.

First, import the array module.

Then, use the array.array() function to create a new array object. The first argument is a type code, which represents the data type of the elements. Some common type codes are:

Type CodeData TypeDescription
bintSigned integer of size 1 byte
BintUnsigned integer of size 1 byte
iintSigned integer of size 2 bytes
IintUnsigned integer of size 2 bytes
ffloatIEEE 754 floating point number of size 4 bytes
dfloatIEEE 754 floating point number of size 8 bytes

The second argument is an iterable object containing the elements of the array. You can use a list, tuple, or any other iterable to initialize the array.

You can access, update, and perform other operations on an array from the array module in the same way as on a list.

Full Code

Conclusion

Now you know how to declare an array in Python using both the built-in list data structure and the array module.

Depending on your requirements, you can choose the method that best suits your needs. Lists provide more flexibility in terms of storing different data types, while the array module enforces a specific data type for all elements.