What is the difference between a python list and an array?



In python, both array and the list are used to store the data as a data structure. In this article, we discuss the difference between a list and an array.

List

Lists are one of the four most commonly used data structures provided by Python. A list is a data structure in python that is mutable and has an ordered sequence of elements. Lists also support negative indexing.

Following is a list of integer values −

lis= [1,2,3,4,5] print(lis)

Output

If you execute the above snippet, produces the following output −

[1, 2, 3, 4, 5]

Array

An array is a data structure that holds data in a linear format. Arrays hold a fixed number of elements and these elements should be homogenous (have the same data type). It's also square bracketed, ordered, mutable, and ordered.

Declaring an array by importing the array module.

In python, we have to import an array module or import NumPy to declare an array.

Example

import array as arr sample_array = arr.array("i", [1, 2, 3, 4]) print(sample_array) print(type(sample_array))

Output

The above code produces the following results

array('i', [1, 2, 3, 4])
<type 'array.array'>

Declaring an array by importing Numpy

In this example, we will declare an array by importing the numpy module.

import numpy as np sample_array = np.array([1, 2, 3, 4]) print(sample_array) print(type(sample_array))

Output

The above code produces the following results

[1 2 3 4]
<class 'numpy.ndarray'>

Differences between a list and an array in python

The following are a few important differences between a list and an array in python.

List Array
Lists are heterogeneous(they can store values of different data types). Arrays are homogenous( they can only store values of the same data type).
There is no requirement for importing any module to declare a list. We need to import module explicitly to declare an array.
Lists cannot handle arithmetic operations Arrays can handle arithmetic operations.
List consumes large memory when compared to an array Arrays are more compact in memory size comparatively list.
Modifications to data items such as insertion, deletion, and update are simple. It is difficult to modify an array since addition, deletion, and update operation is performed on a single element at a time.
It can be nested to hold several types of components. All nested components must be the same size.
We can print the entire list with the help of explicit looping. We can print the entire list without the help of explicit looping.
Lists are preferred for short data sequences. Arrays are preferred for longer data sequences.

Advertisements