Skip to content Skip to sidebar Skip to footer

"'int' Object Is Not Iterable" In While

def rect_extend(x): m, n = 1 while 1 < x: m = m + 1 n = n + 1 return m, n This simple function returns: 'int' object is not iterable error in iPython. I don't k

Solution 1:

When you do m, n = 1 this is called tuple unpacking, and it works like this:

>>>m, n = ('a','b')>>>m
'a'
>>>n
'b'

Since 1 is an integer not a tuple, you get this weird error; because Python cannot "step through" (or iterate) an integer to unpack it. That's why the error is 'int' object is not iterable

Solution 2:

I think you want

m = 1n = 1

or

m = n = 1

instead of m, n = 1.

This (sequence unpacking)[http://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences]:

x, y = z

does something different to what you seem to think it does.

It actually means this:

x = z[0]    # The first item in zy = z[1]    # The second element of z

For instance, you could do this:

x, y, z = (1, 2, 4)

Then:

>>>x
1
>>>y
2
>>>z
4

In your case, you this doesn't work, because 1 is an integer, it doesn't have elements, hence the error.

Useful features of sequence unpacking combined with tuples (and the splat operator - *):

This:

a, b = b, a

swaps the values of a and b.

Unpacking range, useful for constants:

>>>RED, GREEN, BLUE = range(3)>>>RED
0
>>>GREEN
1
>>>BLUE
2

The splat operator:

>>>first, *middle, last = 1, 2, 3, 4, 5, 6, 7, 8, 9>>>first
1
>>>middle
[2, 3, 4, 5, 6, 7, 8]
>>>last
9

Post a Comment for ""'int' Object Is Not Iterable" In While"