What is a tuple useful for?

后端 未结 11 767
天涯浪人
天涯浪人 2021-02-01 12:45

I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type wo

相关标签:
11条回答
  • 2021-02-01 13:11

    I like this explanation.

    Basically, you should use tuples when there's a constant structure (the 1st position always holds one type of value and the second another, and so forth), and lists should be used for lists of homogeneous values.

    Of course there's always exceptions, but this is a good general guideline.

    0 讨论(0)
  • 2021-02-01 13:12

    In addition to the places where they're syntactically required like the string % operation and for multiple return values, I use tuples as a form of lightweight classes. For example, suppose you have an object that passes out an opaque cookie to a caller from one method which is then passed into another method. A tuple is a good way to pack multiple values into that cookie without having to define a separate class to contain them.

    I try to be judicious about this particular use, though. If the cookies are used liberally throughout the code, it's better to create a class because it helps document their use. If they are only used in one place (e.g. one pair of methods) then I might use a tuple. In any case, because it's Python you can start with a tuple and then change it to an instance of a custom class without having to change any code in the caller.

    0 讨论(0)
  • 2021-02-01 13:14

    I find them useful when you always deal with two or more objects as a set.

    0 讨论(0)
  • 2021-02-01 13:14

    A tuple is a sequence of values. The values can be any type, and they are indexed by integer, so tuples are not like lists. The most important difference is that tuples are immutable.

    A tuple is a comma-separated list of values:

    t = 'p', 'q', 'r', 's', 't'
    

    it is good practice to enclose tuples in parentheses:

    t = ('p', 'q', 'r', 's', 't') 
    
    0 讨论(0)
  • 2021-02-01 13:15

    Tuples are used in :

    1. places where you want your sequence of elements to be immutable
    2. in tuple assignments
    a,b=1,2
    
    1. in variable length arguments
    def add(*arg) #arg is a tuple
        return sum(arg)
    
    0 讨论(0)
  • 2021-02-01 13:24
    • Tuples are used whenever you want to return multiple results from a function.
    • Since they're immutable, they can be used as keys for a dictionary (lists can't).
    0 讨论(0)
提交回复
热议问题