Question

Why is it that the follow two code snippets produce different errors? I understand that strings are iterable, but I don't see why that would matter here since the set is the object being iterated over.

s = set([1, 2])        
for one, two in s:
  print one, two

raises

Traceback (most recent call last):
  File "asdf.py", line 86, in <module>
    for one, two in s:
TypeError: 'int' object is not iterable

s2 = set(['a', 'b'])
for one, two in s2:
  print one, two 

raises

Traceback (most recent call last):
  File "asdf.py", line 90, in <module>
    for one, two in s2:
ValueError: need more than 1 value to unpack
Was it helpful?

Solution

A string is a sequence too; you can unpack a string into separate characters:

>>> a, b = 'cd'
>>> a
'c'
>>> b
'd'

The ValueError is raised because a string of length 1 cannot be unpacked into two targets.

When looping over a sequence of integers, however, you are trying to unpack each integer value into two targets, and integers are not iterable at all. That's a TypeError, because this is directly connected to the type of object you are trying to unpack:

>>> a, b = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

Compare this to strings, lists, tuples, iterators, generators, etc. which are all types that are iterable.

If you wanted to unpack the set directly, don't use a for loop:

>>> a, b = set([1, 2])
>>> a
1
>>> b
2

but do know that sets have no fixed order (just like dictionaries), and in what order the values are assigned depends on the exact history of insertions into and deletions from the set.

OTHER TIPS

Your for loop is possibly going deeper than you expect. You're trying to unpack individual members of the set, not the set itself. In the first example the member is 1 and the second the member is a. Neither has two values.

What you possibly want is one, two = s.

You can also find this out by writing:

>>> s = set([1, 2])
>>> for one_two in s:
...     print one_two
1
2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top