Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Python List vs Array – 4 Differences to know!

ARRAY V S LIST

Hey, folks! Hope you all are doing well. In this article, we will be focusing on the Difference between a Python List and Array in detail.


The main difference between a Python list and a Python array is that a list is part of the Python standard package whereas, for an array, the “array” module needs to be imported. Lists in Python replace the array data structure with a few exceptional cases.

1. How Lists and Arrays Store Data

As we all know, Data structures are used to store the data effectively.

In this case, a list can store heterogeneous data values into it. That is, data items of different data types can be accommodated into a Python List.

Example:

lst = [1,2,3,4,'Python']
print(lst)

Output:

[1,2,3,4,'Python']

On the other hand, Arrays store homogeneous elements into it i.e. they store elements that belong to the same type.

Example:

import array

arr = array.array('i', [10, 20, 30, 40])
print(arr)

Output:

array('i', [10, 20, 30, 40])

2. Declaration of Array vs. List

Python has got “List” as a built-in data structure. That is the reason, Lists do not need to be declared in Python.

lst = [1, 2, 3, 4]

On the other hand, Arrays in Python need to be declared. We can declare an array using the below techniques:

Array Module

import array
array-name = array.array('format-code', [elements])

NumPy Module

import numpy
array-name = numpy.array([elements])

3. Superior Mathematical Operations with Arrays

Arrays provide an upper hand when it comes to performing Mathematical operations. The NumPy module provides us with the array structure to store data values and manipulate them easily.

Example with Arrays:

import numpy
arr = numpy.array([1,2,3,4])
pr = arr*5
print(pr)

Output:

[ 5 10 15 20]

Unlike lists, wherein the operations performed on the list do not reflect into the results as seen in the below example with list operations.

Here, we have tried to multiply the constant value (5) with the list, which does not reflect anything in the output. Because Lists are not open to direct mathematical manipulations with any data values.

So, if we want to multiply 5 with the elements of the list, we will have to individually multiply 5 with each element of the list.

Example with Lists:

lst = [1,2,3,4]
pr = lst*5
print(lst)

Output:

[1, 2, 3, 4]

4. Resizing the data structure

Python Lists being an inbuilt data structure can be resized very easily and efficiently.

While on the other side, Arrays prove to have very poor performance in terms of resizing the memory of the array. Instead, we will have to copy the array into another one to scale and resize it.


Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

Till then, Happy Learning!!


References