Returning tuple with a single item from a function

谁说我不能喝 提交于 2019-11-27 09:25:29

You need to explicitly make it a tuple (see the official tutorial):

def returns_tuple_of_one(a):
    return (a, )

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.

(a) is not a single element tuple, it's just a parenthesized expression. Use (a,).

John

Instead of that ugly comma, you can use the tuple() built-in method.

def returns_tuple_of_one(a):
    return tuple(a)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!