In Python, there are three different data structures that can be used to store collections of items: arrays, lists, and tuples. Here are the main differences between them:
Feature | Array | List | Tuple |
---|---|---|---|
Definition | A collection of items that are of the same data type and ordered. | A collection of items that can be of different data types and ordered. | A collection of items that can be of different data types and ordered, but are immutable (cannot be changed). |
Homogeneity | Arrays are homogeneous, which means that they can only store elements of the same data type. | Lists and tuples are heterogeneous, which means that they can store elements of different data types. | |
Mutable vs. Immutable | Arrays and lists are mutable, which means that their elements can be changed after creation. Tuples are immutable, which means that their elements cannot be changed after creation. | ||
Memory Allocation | Arrays allocate memory in contiguous blocks of memory, which makes them more efficient for numerical operations. | Lists allocate memory in non-contiguous blocks, which makes them less efficient for numerical operations. | Tuples allocate memory in the same way as lists. |
Size | Arrays have a fixed size that is set at the time of creation. | Lists can grow or shrink dynamically in size as elements are added or removed. | Tuples have a fixed size that is set at the time of creation. |
Performance | Arrays have faster performance compared to lists for numerical operations due to their contiguous memory allocation. | Lists have slower performance compared to arrays for numerical operations due to their non-contiguous memory allocation. | Tuples have similar performance to lists since they are allocated in the same way. |
Examples | array('i', [1, 2, 3]), array('f', [1.0, 2.0, 3.0]) | [1, 'apple', True], ['red', 'green', 'blue'] | (1, 'apple', True), ('red', 'green', 'blue') |
0 Comments