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

后端 未结 9 1629
悲&欢浪女
悲&欢浪女 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:53

    if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first place?

    In this particular case, there probably isn't a point. This is a non-issue, because this isn't one of the cases where you'd consider using a tuple.

    As you point out, tuples are immutable. The reasons for having immutable types apply to tuples:

    • copy efficiency: rather than copying an immutable object, you can alias it (bind a variable to a reference)
    • comparison efficiency: when you're using copy-by-reference, you can compare two variables by comparing location, rather than content
    • interning: you need to store at most one copy of any immutable value
    • there's no need to synchronize access to immutable objects in concurrent code
    • const correctness: some values shouldn't be allowed to change. This (to me) is the main reason for immutable types.

    Note that a particular Python implementation may not make use of all of the above features.

    Dictionary keys must be immutable, otherwise changing the properties of a key-object can invalidate invariants of the underlying data structure. Tuples can thus potentially be used as keys. This is a consequence of const correctness.

    See also "Introducing tuples", from Dive Into Python.

提交回复
热议问题