Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have known for a while that the primary difference between lists and tuples in Python is that lists are mutable and tuples are not. Beyond that and the different methods available to them, I know very little about lists and tuples. Is there any other difference between them? Are there any advantages/disadvantages (aside from immutability) in using a tuple over a list in Python 3? Does one have a faster access time, or have a smaller memory size, or contain more methods, than the other? Are their internal structures different in any way? Or is a tuple just an immutable list, nothing more?

like image 795
fouric Avatar asked Apr 02 '12 00:04

fouric


2 Answers

Both lists and tuples are internally implemented as arrays of references to the element objects. This way, both can be indexed and both require the same amount of memory for each element. Internally, they are both homogeneous (untyped references). Logically, they are both heterogeneous (automatic dereferencing, the type is bound to the target object).

The list can be modified, so the internal array is a dynamic array. The tuple cannot be modified, so it is internally just fixed-size array. From that point of view, tuples are simpler.

For which is faster or not, you can measure the concrete situation using the timeit module.

You should be aware of the fact that tuples are immutable only with respect to the number and to values of the stored references. If (say) a list is used as one of the tuple elements, the list content can be changed. This way, logically, the tuple content is not constant (such tuple is not hashable).

Use whatever type is better for the purpose. There is no strict preference. It depends on the situation.

like image 113
pepr Avatar answered Oct 07 '22 02:10

pepr


Run dir on both of them - pretty different method list (pop demonstrated below). tuples may 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 all available for lists, and not for tuples - which makes sense, given the immutability idea.

Philosophically, some people expect lists to be homogeneous, and don't have that expectation of tuples.

like image 42
Alex North-Keys Avatar answered Oct 07 '22 03:10

Alex North-Keys