Difference between list and tuple (minus immutability) in Python?

For a while, I knew that the main difference between lists and tuples in Python is that lists are mutable and tuples are not. Besides this and the various methods available to them, I know very little about lists and tuples. Is there any other difference between the two? Are there any advantages / disadvantages (other than immutability) of using a tuple over a list in Python 3? Does it have faster access time or has less memory or contains more methods than the other? Are their internal structures different? Or is a tuple just an immutable list, no more?

+7
source share
2 answers

Both lists and tuples are internally implemented as arrays of references to element objects. Thus, both indexes can be indexed and both require the same amount of memory for each element. Inside, they are both homogeneous (untyped links). Logically, they are both heterogeneous (automatic dereferencing, the type is attached to the target).

The list can be modified, so the internal array is a dynamic array. A tuple cannot be changed, so it is only an array of a fixed size. From this point of view, tuples are simpler.

For what is faster or not, you can measure a specific situation using the timeit module.

You should know that tuples are immutable only with respect to the number and values โ€‹โ€‹of stored links. If (say) a list is used as one of the elements of a tuple, the contents of the list can be modified. Thus, logically, the contents of a tuple are not constant (such a tuple is not hashed).

Use any type that is best suited for this purpose. No strict preference. It depends on situation.

+7
source

Run dir on both of them - a rather different list of methods (pop shown below). tuples can be faster

>>> alist = [1,2,3] >>> atuple = (1,2,3) >>> alist.pop() 3 >>> atuple.pop() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'pop' 

'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort' are available for lists, not for tuples. makes sense given the idea of โ€‹โ€‹immutability.

Philosophically, some people expect lists to be homogeneous and not have this expectation of tuples.

+4
source

All Articles