Difference Between Array and List in Python
The main difference between array and list in Python is that an array will carry the elements of the same data types, whereas a list can have various elements belonging to data types. The significant differences between these two factors of Python are explained in the table provided below:
Key Differences 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, allowing 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.
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 in Python
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.)