Stanisław Borkowski
Stanisław Borkowski

Reputation: 37

Can you create method with tuple of parameters?

Can you do something like this in Python?

def give_me_your_three_favorite_things_in_each_given_category(
    food=(first, second, third), 
    color=(first, second, third))
    println(f"Your favorite foods are {food.first}, {food.second} and {food.third}")
    println(f"Your favorite colors are {color.first}, {color.second} and {color.third}")

give_me_your_three_favorite_things_in_each_given_category(
    food=(first="pizza", second="pasta", third="ice cream"),
    color=(first="black", second="blue", third="green")

Expected output:
"Your favorite foods are pizza, pasta and ice cream"
"Your favorite colors are black, blue and green"

Upvotes: 1

Views: 64

Answers (1)

maor10
maor10

Reputation: 1784

Sure- The way you would do it would be as follows:

def give_me_your_three_favorite_things_in_each_given_category(food, color):
    first_food, second_food, third_food = food
    print(f"Your favorite foods are {first_food}, {second_food}, {third_food}")
    first_color, second_color, third_color = color
    print(f"Your favorite colors are {first_color}, {second_color}, {third_color}")

You can see here that we receive tuples as paramaters, and then unpack them.

You can then call the function with

give_me_your_three_favorite_things_in_each_given_category(
food=("pizza", "pasta", "ice cream"),
color=("black", "blue", "green"))

You can also use named tuples so that you can have names for each value in the tuple:

from collections import namedtuple
Food = namedtuple("Food", ("first", "second", "third"))
Color = namedtuple("Color", ("first", "second", "third"))
give_me_your_three_favorite_things_in_each_given_category(
    food=Food(first="pizza", second="pasta", third="ice cream"),
    color=Color(first="black", second="blue", third="green")
)

Upvotes: 2

Related Questions