When we talk about arrays in the context of C or C++, it refers to a collection of elements of a homogeneous type. But in Python, arrays are usually spoken about in the context of lists. Lists are Pythonic data structures that store data elements of different types.
Python comes with an array module that supports the storage of numeric elements.
Note: One important difference between lists and arrays in Python is that the list can store heterogeneous data types whereas arrays have the ability to store homogeneous data types only.
How to create an array in Python?
An array in Python can be created by importing the array module. The array module contains a method known as array()
which can be used to create an array. As the function used for creating array is also named array()
, hence we have given an alias name to the module array, so as to avoid confusion. When an array is passed to the array()
method of the array module, a type is specified (d
in this example). This refers to the type of data which is supplied to the array, i.e floating-point type.
Time for an example:
import array as ar
my_array = [1.1, 4.5, 6.8, 9.4]
display_array = ar.array('d', my_array)
print(display_array)
Output:
array('d', [1.1, 4.5, 6.8, 9.4])
Different codes for different data types:
Following are the different code values that should be used while initializing an array in python:
Note: The type u
has been deprecated beginning from Python 3.3, hence avoid its usage as much as possible.
How to access elements of an array in Python?
Since arrays are indexed, they can be accessed with the help of square brackets and indices.
Time for an example:
import array as ar
my_array = [1.1, 4.5, 6.8, 9.4]
display_array = ar.array('d', my_array)
print(display_array)
print("First element", display_array[0])
print("Last element", display_array[-1])
print("Third element", display_array[2])
Output:
array('d', [1.1, 4.5, 6.8, 9.4])
First element 1.1
Last element 9.4
Third element 6.8
Conclusion:
In this post, we understood how arrays in Python work, and how they can be accessed. In the upcoming posts, we will see how the elements can be added to the array and deleted from the array in python.