Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 an answer with the same fruitless search terms I was

Looks like tuple unpacking makes it so you can't return a tuple of length 1 if you're expecting to iterate over the return value. Although it seems that looks are deceiving. See the answers.

>>> def returns_list_of_one(a):
...     return [a]
...
>>> def returns_tuple_of_one(a):
...     return (a)
...
>>> def returns_tuple_of_two(a):
...     return (a, a)
...
>>> for n in returns_list_of_one(10):
...    print n
...
10
>>> for n in returns_tuple_of_two(10):
...     print n
...
10
10
>>> for n in returns_tuple_of_one(10):
...     print n
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
551 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

def returns_tuple_of_one(a):
    return (a, )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...