Confusion in understanding tuple and *args in Python

前端 未结 1 927
庸人自扰
庸人自扰 2021-01-22 13:21

I need a function which would be taking variadic arguments. The number of arguments may vary from 1 to N.

def abc(*args):
    print \"ABC\"
    prin         


        
相关标签:
1条回答
  • 2021-01-22 13:46

    Parentheses don't make tuples, commas do. To build a single-element tuple, the correct syntax is

    tup = ("Hello123",)  # parentheses are optional but help readability
    

    which is equivalent to

    tup = "Hello123",
    

    Remember that you can write

    x, y = y, x  # swaps x and y using tuple packing/unpacking
    

    just as well as

    (x, y) = (y, x)
    

    The only exception where parentheses are mandatory is the empty tuple ().

    0 讨论(0)
提交回复
热议问题