Why do we need tuples in Python (or any immutable data type)?

后端 未结 9 1626
悲&欢浪女
悲&欢浪女 2020-11-30 17:19

I\'ve read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don\'t see why the language needs tuples.

Tuples have n

9条回答
  •  星月不相逢
    2020-11-30 17:57

    As gnibbler offered in a comment, Guido had an opinion that is not fully accepted/appreciated: “lists are for homogeneous data, tuples are for heterogeneous data”. Of course, many of the opposers interpreted this as meaning that all elements of a list should be of the same type.

    I like to see it differently, not unlike others also have in the past:

    blue= 0, 0, 255
    alist= ["red", "green", blue]
    

    Note that I consider alist to be homogeneous, even if type(alist[1]) != type(alist[2]).

    If I can change the order of the elements and I won't have issues in my code (apart from assumptions, e.g. “it should be sorted”), then a list should be used. If not (like in the tuple blue above), then I should use a tuple.

提交回复
热议问题