Reputation: 24768
Python 2.7.10 (default, Sep 17 2015, 03:50:35) [GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
>>> def f():
... return True
...
>>>
>>> a,b = f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not iterable
vs
>>> def f():
... return 'True'
...
>>>
>>> a,b = f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
Why the difference ?
Upvotes: 3
Views: 103
Reputation: 155516
TypeError
means "this sort of object can never be used in this context", while ValueError
means "some objects of this sort could be used in this context, but this one has the wrong value". In this case, no bool
can ever be iterated (what would it mean to sequentially process a bool
value by value?), so it's a TypeError
.
str
can be iterated though. str
is a sequence of length 1 str
s representing each character in the string, so 'True'
iterates as 'T'
, 'r'
, 'u'
and 'e'
; a total of four values, but when you need to fill two variables, only str
of length 2 are valid, and all other str
have invalid values, thus the ValueError
. If you'd provided more names to assign to, e.g. a, b, c, d = f()
, or the string was shorter, e.g. "Tr"
, the code would have worked without errors.
Upvotes: 0
Reputation: 71610
It's because bool
object are not iterable, even if bool
object where iterable, it will do the same thing as the second example.
Example:
for i in True:
print(i)
Raises and error:
Traceback (most recent call last):
File "C:\Users\rep\Desktop\code\so.py", line 3517, in <module>
for i in True:
TypeError: 'bool' object is not iterable
But:
for i in 'True':
print(i)
Returns:
T
r
u
e
And also:
to solve them do:
a,b = f(),f()
And as @ggorlen says,do:
def f(): return "Tr"
Then:
a, b = f()
Upvotes: 2