What's the best practice for handling single-value tuples in Python?

前端 未结 9 1589
长发绾君心
长发绾君心 2021-02-19 05:44

I am using a 3rd party library function which reads a set of keywords from a file, and is supposed to return a tuple of values. It does this correctly as long as there are at le

9条回答
  •  Happy的楠姐
    2021-02-19 06:22

    Your tuple_maker doesn't do what you think it does. An equivalent definition of tuple maker to yours is

    def tuple_maker(input):
        return input
    

    What you're seeing is that tuple_maker("a string") returns a string, while tuple_maker(["str1","str2","str3"]) returns a list of strings; neither return a tuple!

    Tuples in Python are defined by the presence of commas, not brackets. Thus (1,2) is a tuple containing the values 1 and 2, while (1,) is a tuple containing the single value 1.

    To convert a value to a tuple, as others have pointed out, use tuple.

    >>> tuple([1])
    (1,)
    >>> tuple([1,2])
    (1,2)
    

提交回复
热议问题