3
votes

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 ?

2
have you tried a,b = f(),f() ?Black Thunder
Try def f(): return "Tr" then call it with a, b = f(). In your first example, you can't unpack something non iterable, second example you're trying to unpack an iterable with 4 items into 2.ggorlen
Note: Nothing about this is specific to Python 2.7; every version of Python since iterable unpacking was introduced has had the behavior described.ShadowRanger

2 Answers

2
votes

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()
0
votes

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 strs 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.