Python Memo 1: Tuple vs. List
Learn about Tuples and Lists in Python, the best use cases for choosing each, and more in this article.
Join the DZone community and get the full member experience.Join For Free
Tuple vs. List
Both Tuple and List can store mixed types of values.
Tuple is immutable and length is fixed. List is mutable and length is not fixed.
If we want to append Tuple, then we have to create a new Tuple:
A negative index is supported in both Tuples and List, meaning last count of value:
Nested Tuple/Nested List:
Conversion with list() and tuple():
- count(item): Returns the number of times the specified element appears in the List/Tuple
- index(item): Returns the index of the specified element in the List/Tuple
- list.reverse(): Reverse the elements of the List (not available in tuple)
- list.sort(): Sorts the elements of a given List in a specific ascending or descending order (not available in Tuple)
- reversed(): Returns an iterator that accesses the given sequence in the reverse order in List/Tuple
- sorted(): Returns a sorted List of the specified iterable object in List/Tuple
As we know, the most difference between Tuple and List is List is mutable and dynamic but Tuple is immutable and static. The difference also determines the way of storing. Let's see the below example.
Tuple storage is less than list, which is understandable because list needs additional pointer to point the value. In addition, due to mutable list, list needs more space in order to trace the storage.
In above example, Python allocates more space each time in order to reduce the cost of add or delete operation. This over-allocating mechanism improves the efficiency: O(1) for adding/deleting element. But Tuple is different. Since its length is fixed and element is immutable, the allocated space is also fixed.
From the above difference, we can come to a conclusion: Tuple is more lightweight and has better performance than List in general.
Furthermore, Python does resouce caching for static data. Due to GC, if some variables are not used, Python recycles the memories and returns to OS.
But for some static variables, like Tuple, if it is not used and doesn't occupy too many spaces, Python caches the memory. Then, next time when we create the same size Tuple, Python doesn't need to request OS for the memory, but allocates the cached memory to improve the program performance.
In below example, we can find out Tuple is 5 times faster to initiate than list.
But in term of index operation, the performance is too insignificant:
- If data are immutable, for example, if you have a function to return longitude and latitude to client, then Tuple should be better.
- If data are mutable, for example, if you have a function to log a user viewed post within a week on a social app, then List should be better.
Opinions expressed by DZone contributors are their own.