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

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

    None of the answers above point out the real issue of tuples vs lists, which many new to Python seem to not fully understand.

    Tuples and lists serve different purposes. Lists store homogenous data. You can and should have a list like this:

    ["Bob", "Joe", "John", "Sam"]
    

    The reason that is a correct use of lists is because those are all homogenous types of data, specifically, people's names. But take a list like this:

    ["Billy", "Bob", "Joe", 42]
    

    That list is one person's full name, and their age. That isn't one type of data. The correct way to store that information is either in a tuple, or in an object. Lets say we have a few :

    [("Billy", "Bob", "Joe", 42), ("Robert", "", "Smith", 31)]
    

    The immutability and mutability of Tuples and Lists is not the main difference. A list is a list of the same kind of items: files, names, objects. Tuples are a grouping of different types of objects. They have different uses, and many Python coders abuse lists for what tuples are meant for.

    Please don't.


    Edit:

    I think this blog post explains why I think this better than I did: http://news.e-scribe.com/397

提交回复
热议问题