How do you return multiple variables in a function?

I’ve been trying to write a piece of code where 2 variables defined in the first function are returned and used in the second function. I’ve tried returning the 2 variables with a comma between them but I keep getting a Type Error.
I would really appreciate if someone told me how to fix this :slight_smile:

Hi @Neat . As a general tip, its always a good idea to let us know what TypeError you got, i.e. the full error message and the full traceback. Also, it is extremely helpful to paste your actual code, between three backticks (check the preview on the right or use the buttons up to), as otherwise we cannot try it ourselves to find set error, debug it and confirm our solutions work, without having to manually retype all of it from scratch.

However, what happened here seems pretty clear. Your function roll_dice returns a 2-tuple (for very beginner purposes, you can think of a little like a list of length 2), of (num1, num2). You then feed that tuple into roll_dice, as a single tuple instead of two separate arguments. To unpack this tuple into two arguments, you can use the * operator in front of it. This is called tuple unpacking. So you’d have


which unpacks the result of roll_dict (the tuple (num1, num2)) into two arguments, num1 and num2. Make sense?

1 Like

If you maintain your code write this:

user_roll(roll_dice()[0], roll_dice()[1])

Instead you refactoring your code:

user_roll(*numbers): ...

1 Like

Doing it this way would make 4 dice rolls instead of 2.

The correct way to do it is


as @CAM-Gerlach said or the more explicit

num1, num2 = roll_dice()
user_roll(num1, num2)