Junior — Middle
What is the difference between array and list data structures in Python?
sobes.tech AI
Answer from AI
In Python, "array" usually refers to a structure from the array module or numpy.array, while "list" refers to the built-in list type.
Main differences:
-
Element types:
listcan contain elements of different types.arrayfrom thearraymodule contains elements of a single type (e.g., only integers).
-
Performance and memory:
arrayis more efficient in memory and speed when working with large homogeneous data.listis more versatile but less efficient.
-
Functionality:
listsupports many operations and is convenient for general programming.arrayhas limited functionality but is suitable for numerical computations.
Example:
import array
# list with different types
lst = [1, 'two', 3.0]
# array with only integers
arr = array.array('i', [1, 2, 3])
print(lst) # [1, 'two', 3.0]
print(arr) # array('i', [1, 2, 3])