Comparison between Lists and Array in Python
Last Updated :
02 Nov, 2023
Python List
Python programming language has four collection data types namely
List, Tuple, Set, and Dictionary
. A list is a mutable and ordered collection i.e., elements of the list can be changed and it maintains the order of insertion of its items. Because of the property of order maintaining, each element of the list has a fixed index and it permits the list to have duplicate elements. In Python, list is very useful as it has the ability to contain non-homogeneous elements. Following are some operations which can be performed on the list:
Python3
IntList = [ 10 , 20 , 30 ]
print (" List of numbers: ")
print (IntList)
StrList = ["Geeks", "For", "Geeks"]
print (" List of Strings: ")
print (StrList)
Non_homogeneous_list = [ 10 , "Geeks", 20.890 ,\
" for ", 30 , "geeks"]
print (" List of non - homogeneous elements: ")
print (Non_homogeneous_list)
print ("Size of the Non - homogeneous list : ",\
len (Non_homogeneous_list))
NewList = ["Geeks", " for ", "Geeks"]
print ("Original List : ", NewList)
NewList.append("the")
print ("After adding an element the"\
" list becomes: ")
print (NewList)
NewList.insert( 3 , " is ")
print ("After adding an element at"\
"index 3 the list becomes: ")
print (NewList)
NewList.extend(["best", "CS", "website"])
print ("After adding 3 elements at the"\
"end, the list becomes: ")
print (NewList)
NewList.remove("the")
print ("After removing an element"\
"the list becomes: ")
print (NewList)
NewList.pop( 3 )
print ("After removing an element "\
" from index 3 the list becomes: ")
print (NewList)
|
Output
List of numbers:
[10, 20, 30]
List of Strings:
['Geeks', 'For', 'Geeks']
List of non-homogeneous elements:
[10, 'Geeks', 20.89, 'for', 30, 'geeks']
Size of the Non-homogeneous list: 6
Original List: ['Geeks', 'for', 'Geeks']
After adding an element thelist becomes:
['Geeks', 'for', 'Geeks', 'the']
After adding an element atindex 3 the list becomes:
['Geeks', 'for', 'Geeks', 'is', 'the']
After adding 3 elements at theend, the list becomes:
['Geeks', 'for', 'Geeks', 'is', 'the', 'best', 'CS', 'website']
After removing an elementthe list becomes:
['Geeks', 'for', 'Geeks', 'is', 'best', 'CS', 'website']
After removing an element from index 3 the list becomes:
['Geeks', 'for', 'Geeks', 'best', 'CS', 'website']
To get more in-depth knowledge about python list click
here
.
Python Array
Python arrays are also a collection but its items are stored at contiguous memory locations. It can store only homogeneous elements(elements of the same data type). Arrays are very beneficial in performing mathematical operations on the elements. Unlike lists, arrays can not be declared directly. To create an array the
array
module must be imported and the syntax of the declaration is different from that of the list. Following are some operations which can be performed on the array:
Python3
import array as arr
a1 = arr.array( 'i' , [ 10 , 20 , 30 ])
print ("Array a1: ", a1)
print ("Elements of the array"\
"a1 is : ", end = " ")
for i in range ( len (a1)):
print (a1[i], end = ", ")
print ()
a2 = arr.array( 'd' , [ 1.5 , 2.4 , 3.9 ])
print ("Elements of the array"\
"a2 is : ", end = " ")
for i in range ( len (a2)):
print (a2[i], end = ", ")
print ()
print ("Original elements of the"\
"array a1 is : ", end = " ")
print ( * a1)
a1.append( 40 )
print ("Elements of the array a1"\
"after adding an element"\
"at last: ", end = " ")
print ( * a1)
a1.insert( 3 , 35 )
print ("Elements of the array a1"\
"after adding an element"\
"at index 3 : ", end = " ")
print ( * a1)
a1.remove( 20 )
print ("Array a1 after removing"\
"element 20 : ", end = " ")
print ( * a1)
a1.pop( 2 )
print ("Array a1 after removing"\
"element of index 2 : ", end = " ")
print ( * a1)
|
Output
Array a1: array('i', [10, 20, 30])
Elements of the arraya1 is : 10, 20, 30,
Elements of the arraya2 is : 1.5, 2.4, 3.9,
Original elements of thearray a1 is : 10 20 30
Elements of the array a1after adding an elementat last: 10 20 30 40
Elements of the array a1after adding an elementat index 3: 10 20 30 35 40
Array a1 after removingelement 20: 10 30 35 40
Array a1 after removingelement of index 2: 10 30 40
To get more in-depth knowledge about python array click
here
.
Similarities in Python list and array
Both array and lists are used for storing the data:
The purpose of both the collection is to store the data. While the list is used to store homogeneous as well as non-homogeneous data, an array can store only homogeneous data.
Python3
import array as arr
Homogeneous_List = ["Geeks", "For", "Geeks"]
print (" List of Strings: ")
print (Homogeneous_List)
Non_homogeneous_list = [ 10 , "Geeks",\
20.890 , " for ", 30 , "geeks"]
print (" List of non - homogeneous elements: ")
print (Non_homogeneous_list)
Homogeneous_array = arr.array( 'd' ,\
[ 1.5 , 2.4 , 3.9 ])
print ("Elements of the array is "\
" : ", end = " ")
for i in range ( len (Homogeneous_array)):
print (Homogeneous_array[i], end = ", ")
|
Output
List of Strings:
['Geeks', 'For', 'Geeks']
List of non-homogeneous elements:
[10, 'Geeks', 20.89, 'for', 30, 'geeks']
Elements of the array is : 1.5, 2.4, 3.9,
List and Array both are mutable:
List, as well as the array, have the ability to modify their elements i.e., they are mutable.
Python3
import array as arr
List1 = ["Geeks", 1 , "Geeks"]
print ("Original list : ", List1)
List1[ 1 ] = " for "
print ("\nModified list : ", List1)
Array1 = arr.array( 'i' , \
[ 10 , 20 , 30 , 37 , 50 , ])
print ("\nOriginal array: ", end = " ")
for i in range ( len (Array1)):
print (Array1[i], end = " ")
Array1[ 3 ] = 40
print ("\nModified array: ", end = "")
for i in range ( len (Array1)):
print (Array1[i], end = " ")
|
Output
Original list: ['Geeks', 1, 'Geeks']
Modified list: ['Geeks', 'for', 'Geeks']
Original array: 10 20 30 37 50
Modified array: 10 20 30 40 50
Elements of both list and array can be accessed by index and iteration:
In order to access the elements of list and array, we have the option of using index number or we can traverse them by iteration.
Python3
import array as arr
List1 = [ 10 , 20 , 30 , 20 , 10 , 40 ]
print ("List1 elements: ", List1, "\n")
print ("Element at index 0 : ", List1[ 0 ])
print ("Element at index 1 : ", List1[ 1 ])
print ("Element at index 3 : ", List1[ 3 ])
print ("Element at index 4 : ", List1[ 4 ])
print ("Element at last index: ", List1[ - 1 ])
print ("Element at "\
" 3rd last index: ", List1[ - 3 ])
print ("Accessing through iteration: ", end = " ")
for item in range ( len (List1)):
print (List1[item], end = " ")
Array1 = arr.array( 'i' ,\
[ 10 , 20 , 30 , 40 , 50 , 60 ])
print ("\nArray1: ", Array1)
print ("Element of Array1"\
" at index 3 : ", Array1[ 3 ])
print ("Accessing through iteration:"\
" ", end = " ")
for i in range ( len (Array1)):
print (Array1[i], end = " ")
|
Output
List1 elements: [10, 20, 30, 20, 10, 40]
Element at index 0: 10
Element at index 1: 20
Element at index 3: 20
Element at index 4: 10
Element at last index: 40
Element at 3rd last index: 20
Accessing through iteration: 10 20 30 20 10 40
Array1: array('i', [10, 20, 30, 40, 50, 60])
Element of Array1 at index 3: 40
Accessing through iteration: 10 20 30 40 50 60
List and array both can be sliced:
Slicing operation is valid for both the list and array to get a range of elements.
Python3
import array as arr
List1 = [ 10 , 20 , 30 , 20 , 10 , 40 ]
print (" List elements from "\
"index 1 to 4 : ", List1[ 1 : 4 ])
print (" List elements from "\
"index 2 to last: ", List1[ 2 :])
Array1 = arr.array( 'i' ,
[ 10 , 20 , 30 , 40 , 50 , 60 ])
Sliced_array1 = Array1[ 1 : 4 ]
print ("\nSlicing elements of the "\
"array in a\nrange from index 1 to 4 : ")
print (Sliced_array1)
Sliced_array2 = Array1[ 2 :]
print ("\nSlicing elements of the "\
"array from \n2nd index till the end: ")
print (Sliced_array2)
|
Output
List elements from index 1 to 4: [20, 30, 20]
List elements from index 2 to last: [30, 20, 10, 40]
Slicing elements of the array in a
range from index 1 to 4:
array('i', [20, 30, 40])
Slicing elements of the array from
2nd index till the end:
array('i', [30, 40, 50, 60])
Differences between the Python list and array:
Difference in creation:
Unlike list which is a part of Python syntax, an array can only be created by importing the array module. A list can be created by simply putting a sequence of elements around a square bracket. All the above codes are the proofs of this difference.
Memory consumption between array and lists:
List and array take a different amount of memory even if they store the same amount of elements. Arrays are found to be more efficient in this case as they store data in a very compact manner.
Python3
import array as arr
import sys
List = range ( 1000 )
print ("Size of each element of"\
" list in bytes: ", sys.getsizeof( List ))
print ("Size of the whole list in "\
" bytes: ", sys.getsizeof( List ) * len ( List ))
Array = arr.array( 'i' , [ 1 ] * 1000 )
print ("Size of each element of "\
"the array in bytes: ", Array.itemsize)
print ("Size of the whole array"\
" in bytes: ", len (Array) * Array.itemsize)
|
Output
Size of each element of list in bytes: 48
Size of the whole list in bytes: 48000
Size of each element of the array in bytes: 4
Size of the whole array in bytes: 4000
Performing mathematical operations:
Mathematical operations like dividing or adding each element of the collection with a certain number can be carried out in arrays but lists do not support these kinds of arithmetic operations. Arrays are optimized for this purpose while to carry out these operations in the list, operations have to be applied to every element separately.
Python3
from numpy import array
List = [ 1 , 2 , 3 ]
Array = array([ 1 , 2 , 3 ])
try :
List = List + 5
except (TypeError):
print ("Lists don't support list + int ")
try :
Array = Array + 5
print ("Modified array: ", Array)
except (TypeError):
print ("Arrays don't support list + int ")
|
Output
Lists don't support list + int
Modified array: [6 7 8]
Resizing:
Arrays once declared can not be resized. The only way is to copy the elements of the older array into a larger sized array. While the list can be re-sized very efficiently.
Data that can be stored:
List can store both homogeneous as well as non-homogeneous data while arrays support the storage of only homogeneous data.
Similar Reads
Case-insensitive string comparison in Python
The goal here is to compare strings in a list without considering their case, meaning the comparison should ignore whether letters are uppercase or lowercase. For example, given the list ["hello", "HELLO", "HeLLo"], we want to check if all strings are equal, ignoring the case. Let's explore differen
2 min read
Python - Like Index Common characters
Sometimes we come across this type of problem in which we require to intersect each element of one list with the other. This type of problems usually occurs in developments in which we have the combined information, like names and surnames in different lists. Letâs discuss certain ways in which this
3 min read
Test if all elements are present in list-Python
The task of testing if all elements are present in a list in Python involves checking whether every item in a target list exists within a reference list. For example, given two lists a = [6, 4, 8, 9, 10] and b = [4, 6, 9], the task is to confirm that all elements in list b are also found in list a.
3 min read
Python - List Elements Grouping in Matrix
Given a Matrix, for groups according to list elements, i.e each group should contain all elements from List. Input : test_list = [[2, 6], [7, 8], [1, 4]], check_list = [1, 2, 4, 6] Output : [[7, 8], [[1, 2], [4, 6]]] Explanation : 1, 2, 4, 6 elements rows are grouped. Input : test_list = [[2, 7], [7
8 min read
Python | Check if all elements in a list are identical
Given a list, write a Python program to check if all the elements in that list are identical using Python. Examples: Input : ['a', 'b', 'c'] Output : False Input : [1, 1, 1, 1] Output : TrueCheck if all elements in a list are identical or not using a loop Start a Python for loop and check if the fir
5 min read
Python - Test if any set element exists in List
Given a set and list, the task is to write a python program to check if any set element exists in the list. Examples: Input : test_dict1 = test_set = {6, 4, 2, 7, 9, 1}, test_list = [6, 8, 10] Output : True Explanation : 6 occurs in list from set. Input : test_dict1 = test_set = {16, 4, 2, 7, 9, 1},
4 min read
Python | Calculate difference between adjacent elements in given list
The task of calculating the difference between adjacent elements in a list involves iterating through the list and computing the difference between each consecutive pair. For example, given a list a = [5, 4, 89, 12, 32, 45], the resulting difference list would be [-1, 85, -77, 20, 13], Using numpy N
3 min read
Python | Check if all elements in a List are same
To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. [GFGTABS] Python a = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) [/GFGTABS]OutputTrue Ex
3 min read
Python - Check List elements from Dictionary List
Sometimes, while working with data, we can have a problem in which we need to check for list element presence as a particular key in list of records. This kind of problem can occur in domains in which data are involved like web development and Machine Learning. Lets discuss certain ways in which thi
4 min read
Python | Check for Nth index existence in list
Sometimes, while working with lists, we can have a problem in which we require to insert a particular element at an index. But, before that it is essential to know that particular index is part of list or not. Let's discuss certain shorthands that can perform this task error free. Method #1 : Using
3 min read