user3448578
user3448578

Reputation: 39

Python - Separate tuples from the return of another function into different variable

I have a function that return 2 values that are 2 tuples in a couple. Here is the function:

def validate_move(self):
    import ast
    source = tuple(int(x.strip()) for x in input("position:").split(','))
    target = tuple(int(x.strip()) for x in input("position:").split(','))
    if self.validate_position_source(source) == True:
        if self.validate_position_target(source, target) == True:
            return source, target

A return looks like this:

((3, 2), (1, 4))

The first tuple being source and the second target.I want to have both tuples into a variable in another function. For example here,

a = (3,2)
b= (1,4)

I know i have to call the function but i don't know how to "extract" the tuples into the variables.

Upvotes: 0

Views: 548

Answers (2)

Emilia Bopp
Emilia Bopp

Reputation: 883

This should work:

source, target = your_object.validate_move()

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121744

Just assign to multiple variables:

a, b = obj.validate_move()

Python will unpack the return value for you and assign each element to the different targets named to the left of the = assignment.

You could also just address each element in the tuple:

result = obj.validate_move()
a = result[0]
b = result[1]

but the unpacking assignment is much more convenient.

Upvotes: 2

Related Questions