0

if a tuple is iterable why the following code results to an error? I have read many threads about this but I am not able to understand.

tp1 = (5,7) 
for i,j in tp1:
    print(i,j)
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
Navy Alsk
  • 27
  • 8

3 Answers3

3

If a tuple is iterable why the following code results to an error?

Because for i, j in (5, 7, ..., n) is essentially equivalent to:

i, j = 5
i, j = 7
...
i, j = n

And the resulting int on the right-hand side is not iterable. You cannot "unpack"* each element of the tuple further because it is a single integer.

What you can do is the more straightforward assignment:

tp1 = (5, 7)
i, j = tp1

The syntax that you're currently using would apply if each element of the tuple is iterable, such as :

>>> tp2 = (['a', 5], ['b', 6])
>>> for i, j in tp2: print('%s -> %d' % (i, j))
... 
a -> 5
b -> 6

*From comments: Can you explain to me what you mean with the phrase 'you cannot "unpack" each element of the tuple further because it is a single integer'?

Unpacking is the concept of expanding or extracting multiple parts of a thing on the right hand side into multiple things on the left-hand side. Unpacking, extended unpacking, and nested extended unpacking gives a thorough overview of unpacking. There are also some extended forms of unpacking syntax specified in PEP 3132.

Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • @thank you all for your response .however can you explain to me what you mean with the phrase "you cannot "unpack" each element of the tuple further because it is a single integer"?thank you again a lot! – Navy Alsk Jun 09 '20 at 17:25
  • 1
    check my answer i think it will give you answer of this question – Ritik Kumar Jun 09 '20 at 17:27
3

When you use the for i,j in tp1: syntax, Python is expecting that item is an iterable of iterables, which can be unpacked into the variables i and j. In this case, when you iterate over item, the individual members of item are int's, which cannot be unpacked

if you want to unpack the items in the tuple, you should do it like this:

for i in tp1:
    print(i)

and if you want to iterate throught that way you need tuple or list inside tuple or list (i.e any iterable inside iterable)

a = [(1,2), (3,4)] 
for i, j in a:  # This unpacks the tuple's contents into i and j as you're iterating over a
    print(i, j)

hope it would help you

Ritik Kumar
  • 661
  • 5
  • 16
1

Your for loop is trying to unpack a tuple from each element of the tuple. You could instead do:

for i in tp1:
    print i

or you could just do:

i, j = tpl
print(i, j)

but combining the two only makes sense if you have a tuple of tuples, like ((5, 7), (9, 11)).

Samwise
  • 68,105
  • 3
  • 30
  • 44