I've just read in "Dive into Python" that "tuples are faster than lists".
Tuple is immutable, and list is mutable, but I don't quite understand why tuple is faster.
Anyone did a performance test on this?
I've just read in "Dive into Python" that "tuples are faster than lists".
Tuple is immutable, and list is mutable, but I don't quite understand why tuple is faster.
Anyone did a performance test on this?
In python, we have two types of objects. 1. Mutable, 2. Immutable.
In python, lists come under mutable objects and tuples comes under immutable objects.
Tuples are stored in a single block of memory. Tuples are immutable so, It doesn't require extra space to store new objects.
Lists are allocated in two blocks: the fixed one with all the Python object information and a variable-sized block for the data.
It is the reason creating a tuple is faster than List.
It also explains the slight difference in indexing speed is faster than lists, because in tuples for indexing it follows fewer pointers.
Tuples are that they use less memory where lists use more memory.
We can use tuples in a dictionary as a key but it's not possible with lists.
We can access elements with an index in both tuples and lists.
We cannot add an element to tuple but we can add an element to list.
We can't sort a tuple but in a list, we can sort by calling
list.sort() method.
We can't remove an element in tuple but in a list, we can remove an element.
We can't replace an element in tuple but you can in a list.
Tuples are identified by python compiler as one immutable constant so compiler created only one entry in hash table and never changed
Lists are mutable objects.So compiler update the entry when we update the list so it is little bit slower compare to tuple