JustBlossom
JustBlossom

Reputation: 1329

Unpack error with tuple of tuples?

I want to iterate over the elements ((a,b),(x,y)) so I tried:

def method(tuple):
    ((a,b),(x,y))= tuple
    for element in tuple:
    .....

But then I read another stackoverflow page which suggested something like this:

def method(tuple):
    ((a,b),(x,y))= tuple
    for element in tuple[0:4]:
    .....

Both resulted in the error: ValueError: need more than 1 value to unpack.

Is this action not allowed in python, or do I just have a syntax problem? I have checked the python docs as well.

Thanks for any advice.

Edit

map = ((1,0),(3,2))
    def count(map):
        ((a,b),(x,y))= tuple
        inc=0
        for element in tuple:
            inc+=1

Upvotes: 1

Views: 3969

Answers (1)

Christian Tapia
Christian Tapia

Reputation: 34176

If you have a tuple of tuples, of the form ((a, b), (x, y)), you can iterate over its elements:

def method(tuples):
    for tup in tuples:
        for e in tup:
            print e

If you want to have 4 variables, you can use them separately:

def method(tuples):
    (a, b), (x, y) = tuples
    print a, b, x, y

Note: Don't use Python built-in names as name of variables. In other words, don't use tupleas a name of a variable because it's a type in Python. Use something else, like tuples, my_tuple, ...

Upvotes: 8

Related Questions