Search code examples
pythonsequenceiterable-unpacking

Unpacking sequences in python


I started learning python few weeks ago(with no previous knowledge in programming), and went onto the following problem related to unpacking of sequences, which confuses me a lot.

For some reason when I try this:

for b, c in [1,2]:
    print b,c

I am getting an error message:

TypeError: 'int' object is not iterable

The same happens when I try to replace the list with a tuple (1,2)

But when I try the same thing, just with a tuple inside of list:

for b, c in [(1,2)]:
    print b,c

it works - I get:

1 2

Why is that?

Thank you.

btw I am using Python 2.7


Solution

  • Everytime you do a in <iterable> statement, it fetches one item from the iterable and then unpacks it according to your needs, in your case b, c. So, in the first example, you try to assign b, c to 1 which is not possible, whereas in next example you do b, c = (1, 2) which unpacks successfully and gives you a b, c.

    For example, try to print out the values.

    >>> for x in [1, 2]:
            print "X: ", x
    
    
    X:  1
    X:  2
    
    >>> for x in [(1, 2)]:
            print "X: ", x
    
    
    X:  (1, 2)
    

    So, assigning b, c = 1 is not possible, whereas assigning b, c = (1, 2) is possible.