Tell me please, do I understand correctly that the main advantage of a tuple over a list is the size and speed of access?

#!/usr/local/lib/python3 q = (1,2,3) w = [1,2,3] print(q.__sizeof__()) # 48 print(w.__sizeof__()) # 64 

The remaining differences such as the ability to use a tuple in the form of a key for the dictionary are rather exotic and rarely used.

  • one
    well, another tuple is immutable .. this kind of protection "from a fool" and the possibility of shots in his own leg. - Bogdan
  • Not really. If the elements of the tuple are changeable, then they can be changed) - rettoryh13
  • one
    Useful article [Habr] [1] [1]: habr.com/en/en/post/417783 - Andrey Golubev
  • @ rettoryh13, but the links will remain unchanged. If we give an analogy from C ++, it will be a constant pointer. - Bogdan
  • one
    I would not say that using a tuple as a key of a dictionary or an element of a set is something exotic. - Xander

1 answer 1

  1. The size
  2. Speed
  3. Immutability
  4. The tuple can be used as a dictionary key due to immutability
  5. Various allowed operations aaa=(1,2) aaa[0]=0 # TypeError bbb=[1,2] bbb[0]=2 bbb # [2,2]
  6. The tuple is a hashable object, and the list is not hash(aaa) # 1278979879 hash(bbb) # TypeError: unhashable type: 'list'
  7. Foolproof
  8. Using where one value does not make sense without another
  • You can still add namedtuple there :) - gil9red
  • @nick_gabpe I understand correctly that points 2 and 6 are connected? - rettoryh13
  • @ rettoryh13 no. This is all because of the immutability. As I understand it: a tuple is created once and created as a constant. Then he simply "spies" the value of this constant somewhere inside his table of constants. The list is created, but then it can change and the interpreter needs to watch every time 1) how many elements the list has and 2) what their value is right now, and this takes some time. But this is how I understand it, and I could be wrong. - nick_gabpe
  • @ gil9red is possible, I read about it, but I didn’t come across it myself, so I can write nonsense :) - nick_gabpe February