Lycon Lycon - 1 month ago 8
Python Question

How can I return two values from a function in Python?

I would like to return two values from a function in two separate variables.
For example:

def select_choice():
loop = 1
row = 0
while loop == 1:
print('''Choose from the following options?:
1. Row 1
2. Row 2
3. Row 3''')

row = int(input("Which row would you like to move the card from?: "))
if row == 1:
i = 2
card = list_a[-1]
elif row == 2:
i = 1
card = list_b[-1]
elif row == 3:
i = 0
card = list_c[-1]
return i
return card


And I want to be able to use these values separately. When I tried to use
return i, card
, it returns a
tuple
and this is not what I want.

Answer

Return a tuple/list (or any other sequence, e.g. dict) and unpack it after the call:

def select_choice():
    ...
    return i, card  # or [i, card]

my_i, my_card = select_choice()

In the line return i, card i, card means creating a tuple. You can also put in parenthesis like return (i, card), but the tuple is created by the comma, so parens are not mandatory, but you can use them to make your code more readable or split the tuple over multiple lines.