What is an Array in Python?
An array in Python is a vector that contains homogeneous elements, i.e. belonging to the same data type. Elements are addressed with contiguous memory locations that allow easy modification, like addition, deletion, and accessing of elements. Array module is used to declare arrays. In python, if the elements of an array belong to different data types, then an exception called “Incompatible data types” is thrown.
Example of an array:
sample_array = array.array('i', [1, 2, 3])
# accessing elements of array
for i in sample_array:
What is a List in Python?
A list in Python is a collection of items that contain elements of multiple data types. The data type may be either numeric, character logical values, etc. A list is an ordered collection supporting negative indexing. It can be created by using “[ ]” these brackets contains data values. Contents of lists in python can be easily merged and copied using its inbuilt functions.
Example of a List in Python:
sample_list = [1,"Mohit",['a','e']]
[1, 'Mohit', ['a', 'e']]
(The first element is an integer type, the second is a string, and the third one is a list of characters.)
What is the Difference Between Array and List in Python?
We have already seen a brief introduction to Array and List in Python. We will now discuss and explore the difference between Array and List in Python. The significant differences between these two factors of Python are explained in the table provided below:
Difference Between Array and List in Python
Array in Python
List in Python
Array in Python only contains elements that belong to the same data type.
List in Python can contain elements belonging to different data types
It is required to import a module for declaration explicitly.
It does not require explicitly importing a module for declaration.
The array can directly handle arithmetic operations.
A list cannot directly handle arithmetic operations.
The array must consist of all nested elements of the same size.
A list can be nested to consist of different types of elements in size.
It is preferred for an extended sequence of data items.
It is preferred for a short sequence of data items.
It has less flexibility because the addition or deletion has to be done element-wise.
It has greater flexibility that allows easy modification, like adding or deleting data.
In Array, a loop has to be created or printed or accessed the components.
The list can print the whole list without any explicit looping.
The array is more compact in-memory size comparatively.
A list consumes more memory for easy addition of elements.