Difference Between List and Array in Python
Difference Between List and Array in Python
geeksforgeeks.org/difference-between-list-and-array-in-python
In Python, lists and arrays are the data structures that are used to store multiple items.
They both support the indexing of elements to access them, slicing, and iterating over the
elements. In this article, we will see the difference between the two.
Accessing an element in a Python List is the same as an Array because a List is actually
a dynamic array . Inserting or deleting elements at the beginning or in the middle of a list
can be less efficient because it may require shifting all subsequent elements, which is a
linear-time operation in the worst case.
Example:
In this example, we are creating a list in Python. The first element of the list is an integer,
the second a Python string, and the third is a list of characters.
Python3
1/4
# creating a list containing elements
print(type(sample_list))
print(sample_list)
Output:
<class 'list'>
[1, 'Yash', ['a', 'e']]
Example:
In this example, we will create a Python array by using the array() function of the array
module and see its type using the type() function.
Python3
print(type(a))
for i in a:
Output:
<class 'array.array'>
1 2 3
2/4
Difference Between List and Array in Python
The following table shows the differences between List and Array in Python:
List Array
No need to explicitly import a module for Need to explicitly import the array module
the declaration for declaration
Preferred for a shorter sequence of data Preferred for a longer sequence of data
items items
Greater flexibility allows easy Less flexibility since addition, and deletion
modification (addition, deletion) of data has to be done element-wise
The entire list can be printed without any A loop has to be formed to print or access
explicit looping the components of the array
Nested lists can be of variable size Nested arrays has to be of same size.
3/4
List Array
Can perform direct operations using Need to import proper modules to perform
functions like: these operations.
count() – for counting a particular
element in the list
sort() – sort the complete list
max() – gives maximum of the list
min() – gives minimum of the list
sum() – gives sum of all the elements in
list for integer list
index() – gives first index of the element
specified
append() – adds the element to the end
of the list
remove() – removes the element
specified
Example: Example:
my_list = [1, 2, 3, 4] import array
arr = array.array(‘i’, [1, 2, 3])
4/4