Unpack a list in Python?

前端 未结 3 642
感动是毒
感动是毒 2020-11-21 23:10

I think \'unpack\' might be the wrong vocabulary here - apologies because I\'m sure this is a duplicate question.

My question is pretty simple: in a function that ex

相关标签:
3条回答
  • 2020-11-21 23:41

    Since Python 3.5 you can unpack unlimited amount of lists.

    PEP 448 - Additional Unpacking Generalizations

    So this will work:

    a = ['1', '2', '3', '4']
    b = ['5', '6']
    function_that_needs_strings(*a, *b)
    
    0 讨论(0)
  • function_that_needs_strings(*my_list) # works!
    

    You can read all about it here.

    0 讨论(0)
  • 2020-11-21 23:47

    Yes, you can use the *args (splat) syntax:

    function_that_needs_strings(*my_list)
    

    where my_list can be any iterable; Python will loop over the given object and use each element as a separate argument to the function.

    See the call expression documentation.

    There is a keyword-parameter equivalent as well, using two stars:

    kwargs = {'foo': 'bar', 'spam': 'ham'}
    f(**kwargs)
    

    and there is equivalent syntax for specifying catch-all arguments in a function signature:

    def func(*args, **kw):
        # args now holds positional arguments, kw keyword arguments
    
    0 讨论(0)
提交回复
热议问题