Returning tuple with a single item from a function

前端 未结 4 2043
挽巷
挽巷 2020-12-01 21:14

Just came across this little bit of weirdness in Python and thought I\'d document it write it as a question here in case anyone else is trying to find

4条回答
  •  旧时难觅i
    2020-12-01 21:24

    This is not a bug, a one-tuple is constructed by val, or (val,). It is the comma and not the parentheses that define the tuple in python syntax.

    Your function is actually returning a itself, which is of course not iterable.

    To quote sequence and tuple docs:

    A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.

提交回复
热议问题