Python unpacking operator (*)

后端 未结 2 656
慢半拍i
慢半拍i 2021-01-04 10:48

I was researching about python codegolf and saw someone use the unpacking operator in a strange way:

*s,=\'abcde\'

I know that the unpackin

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-04 11:29

    This is Iterable Unpacking. You may have seen it in other places to assign values to multiple variables from a single expression

    a, b, c = [1, 2, 3]
    

    This syntax includes a * to indicate that this variable should be a list containing the elements from the iterable that weren't explicitly assigned to another variable.

    a, *b, c = [1, 2, 3, 4, 5]
    print(b)
    # [2, 3, 4]
    

    So, what's going on in your example? There's only a single variable name being assigned to, so it's going to take all the items not assigned to another variable, which in this case is all of them. If you try just

    *s='abcde'
    

    you'll get

    SyntaxError: starred assignment target must be in a list or tuple
    

    Which is why that comma is there, as a trailing comma is how you indicate a single-value tuple.

提交回复
热议问题