You are currently viewing Difference Between List and Array in Python

What is the difference between a list and an array in Python? A list is a built-in data structure that represents an ordered collection of elements. It is highly flexible and allows storing elements of different data types within the same list. Lists support various operations such as appending, extending, slicing, sorting, and more. They dynamically resize themselves as elements are added or removed, providing convenience at the cost of memory efficiency.

Advertisements

On the other hand, the Python array module provides a way to store and manipulate homogeneous numeric data efficiently. Unlike lists, arrays require all elements to be of the same data type, typically numeric types like integers or floats. By specifying the type of data stored in the array, it can be more memory-efficient compared to lists. The array module also offers a limited set of operations but allows for faster computations on the entire array, especially when dealing with large amounts of numerical data.

In this article, I will explain the list and array and their differences with examples.

1. Quick Examples of List vs Array

If you are in a hurry, below are some quick examples of the difference between a list and an array.


# Quick examples of list vs array

# Example 1: Creating a list of items
# belonging to different data types
mylist = [2,"Sparkbyexample",['Python','Java']]

# Example 2: Get element from the list by 
# Using index
result = mylist[0]

# Example 3: Using array() method
result = array("i", mylist)

# Example 4: Accessing elements of array
sample_array = array.array('i', [2, 4, 6, 8, 10]) 
for i in sample_array:
     print(i)

# Example 5: Using numpy array
myarray = np.array(mylist)

2. What is a List in Python

A list is a built-in data structure that represents an ordered collection of elements. It is one of the most commonly used data structures in Python due to its flexibility and versatility. It is a mutable data structure, meaning its contents can be modified after they have been created. In Python, Lists are typically used to store data that needs to be sorted, searched, or altered in some way. They can also be used to perform operations on a set of data quickly. In a list, the elements are enclosed in square brackets [] and separated by commas. Each element in a list can be of any data type, such as numbers, strings, booleans, lists, tuples, or even other complex objects.

2.1 Creating a List of Items Belonging to Different Data Types

You can create a list that contains items of different data types. For example, a list named mylist is created, containing three elements of different data types, the integer 2, the string "Sparkbyexample", and another list ['Python','Java']. The output displays the original list [2,'Sparkbyexample',['Python','Java']], where each element is separated by commas. The list contains an integer, a string, and a nested list. Lists in Python provide the flexibility to store elements of different data types within the same list. This allows for versatile data storage and manipulation capabilities.


# creating a list of items
# belonging to different data types
mylist = [2,"Sparkbyexample",['Python','Java']]
print("Create a list",mylist)
print("Data type :", type(mylist))

Yields below output.

python difference between list array

2.2 Accessing Elements of a List

You can access list elements using their corresponding index. List elements are indexed starting from 0, so the first element in a list has an index of 0, the second element has an index of 1, and so on.


# Get element from list by 
# using index
result = mylist[0]
print("Given list:", mylist)
print("Get first element from list by index:", result)

# Output:
# Given list: [2,"Sparkbyexample",['Python','Java']]
# Get first element from list by index: 2

3. What is an Array in Python

Python’s array module provides an array data structure that has specific characteristics, as mentioned earlier. Arrays created with the array module require importing the module explicitly and having elements of the same data type. They provide efficient storage and arithmetic operations for numeric values. The array module provides an efficient way to store and manipulate homogeneous numeric data (elements of the same type) like integers, floats, etc. Unlike a list, an array allows you to define the type of data that can be stored in it, which can be more memory-efficient and can lead to faster operations on the array.

3.1 Declaring an Array by Importing the Array Module

You can use the array() function in Python is an inbuilt function provided by the array module to create an array from a list or a tuple. It is a convenient and efficient way to work with arrays in Python. To create an array of integers using the array() function, you can use the i data type. Here, the first argument to the array() function is the data type indicator 'i', which indicates that the array will contain integers. The second argument is the input list mylist.


from array import array

# Initialize list
mylist = [2, 4, 6, 8, 10]
print("Given list: ", mylist)

# Using array() method to create an array
result = array("i", mylist)
print('Create an array:', result)
print("Data type:", type(result))

Yields below output.

python difference between list array

3.2 Accessing Elements of Array

You can access elements of an array in Python using a for loop. For example, an array named sample_array is created using the array() function. It contains the values [2, 4, 6, 8, 10]. The first argument to array() is the type code "i", indicating signed integers. The code uses a for loop to iterate over the elements in an array(sample_array). Each element is assigned to the variable i in each iteration. Within the loop, the value i is printed using the print() function.


import array
 
sample_array = array.array('i', [2, 4, 6, 8, 10]) 
 
# Accessing elements of an array
# using for loop
for i in sample_array:
     print(i)
     
# Output:
# 2
# 4
# 6
# 8
# 10

3.3 Using Numpy Array

The np.array() method is a function from the NumPy library in Python that creates an array object. It takes an iterable, such as a list or a tuple, as its argument and returns a new array with the same elements. For example, you import the NumPy library and create a list mylist with the elements [2, 4, 6, 8, 10]. You then use the np.array() method to create a new array myarray with the same elements as mylist.


import numpy as np

mylist = [2, 4, 6, 8, 10]
print("Given list: ", mylist)

# Using numpy array
myarray = np.array(mylist)
print("Create numpy array: ", myarray)
print("Type of data structure is :",type(myarray))

# Output:
# Given list:  [10, 20, 30, 40, 50]
# Create numpy array :  [10 20 30 40 50]
# Type of data structure is : <class 'numpy.ndarray'>

4. Difference Between List and Array

The following table shows the difference between the list and the array.

List Array
Contains elements of different data types – Lists in Python can hold elements of different data types, such as integers, strings, floats, and even other lists or objects.Contains elements of the same data types – Arrays in Python typically contain elements of the same data type, such as integers or floats. This restriction allows for efficient storage and manipulation of the elements.
Explicitly importing modules is not required to declare a list – Lists are a built-in data type in Python, so you don’t need to import any modules to use them. They can be directly declared and manipulated.Need to import the module explicitly to declare an array – In Python, you need to import the array module explicitly to use arrays. The array module provides a way to create and manipulate arrays in Python.
Cannot handle arithmetic operations – Lists in Python are not designed for arithmetic operations directly on the entire list.Can handle arithmetic operations – Arrays in Python can handle arithmetic operations, such as addition, subtraction, multiplication, and division, between arrays and individual elements.
Can be nested inside another list – Lists can be nested within other lists, forming a multi-dimensional structure.Must contain all elements of the same size – Arrays in Python require all elements to have the same size.
Mostly used in the shorter sequence of data elements – Lists are commonly used to store a sequence of data elements.Mostly used in the longer sequence of data elements – Arrays are often used when dealing with larger sequences of data elements.
Easy modifications like addition, deletion, and update of data elements are done – Lists in Python are mutable, which means you can modify their elements after creation. You can add elements using the append() or extend() methods, delete elements using the del statement or the remove() or pop() methods, and update elements by assigning new values to specific positions in the list.It is difficult to modify an array since addition, deletion, and update operations are performed on a single element at a time – Modifying an array in Python can be more challenging compared to lists. Arrays are fixed in size after creation, so adding or removing elements requires creating a new array with the desired modifications.
We can print the entire list without the help of an explicit loop – You can print the entire list using a single print() statement without needing an explicit loop.To print or access array elements, we will require an explicit loop – When printing or accessing elements in an array, you typically need to use an explicit loop to iterate over the elements and perform the desired operation on each element.
For easy addition of elements, large memory storage is required – When adding elements to a list, memory storage is required to accommodate the new elements.In comparison to the list, it is more compact in-memory size – Arrays generally have a more compact memory representation compared to lists because they store elements in a contiguous block of memory.
Difference between a list and an array

Conclusion

In this article, I have explained the difference between a list and an array in Python. Also, learning, a list, and an array are two different data structures that serve different purposes with examples.

Happy Learning !!