Python provides multiple data structures for storing collections of values, among which Lists and Arrays are two commonly used options. While both support indexing, iteration and storage of multiple elements, they differ significantly in terms of memory usage, data type flexibility and performance.
Lists
A list is a built-in Python data structure used to store an ordered collection of elements that can belong to different data types. Lists are dynamic, meaning their size can change during execution.
- Stores heterogeneous data like numbers, strings, objects, etc.
- Supports dynamic resizing (easy insertion and deletion)
- Allows duplicate values
- Supports indexing, slicing and nesting
Example:
In this example, we are creating a list in Python. The first element of the list is an integer, the second is a Python string and the third is a list of characters.
sample_list = [1, "Yash", ['a', 'e']]
print(type(sample_list))
print(sample_list)
Output:
<class 'list'>
[1, 'Yash', ['a', 'e']]
Arrays
An array is a data structure that stores elements of the same data type in contiguous memory locations, making it efficient for numerical operations. Arrays require the array module to be used.
- Stores homogeneous data only
- Uses less memory than lists
- Faster for numerical and mathematical operations
- Better suited for large numeric datasets
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.
import array as arr
a = arr.array('i', [1, 2, 3])
print(type(a))
for i in a:
print(i, end=" ")
Output:
<class 'array.array'>
1 2 3
Difference Between List and Array in Python
The following table shows the differences between List and Array in Python:
