Understanding *x ,= lst

前端 未结 4 1511
礼貌的吻别
礼貌的吻别 2021-01-30 12:22

I\'m going through some old code trying to understand what it does, and I came across this odd statement:

*x ,= p

p is a list in t

4条回答
  •  滥情空心
    2021-01-30 12:58

    You can clearly understand it from below example

    L = [1, 2, 3, 4]
    while L:
        temp, *L = L             
        print(temp, L)
    

    what it does is, the front variable will get the first item every time and the remaining list will be given to L.

    The output will look shown below.

    1 [2, 3, 4]
    2 [3, 4]
    3 [4]
    4 []
    

    Also look at below example

    x, *y, z = "python"
    print(x,y,z)
    

    In this both x,z will get each one letter from the string meaning first letter is assigned to x and the last letter will be assigned to z and the remaining string will be assigned to variable y.

    p ['y', 't', 'h', 'o'] n
    

    One more example,

    a, b, *c = [0,1,2,3]
    print(a,b,c)
    
    0 1 [2,3]
    

    Boundary case: If there is nothing remaining for star variable then it will get an empty list.

    Example:

    a,b=[1]
    print(a,b)
    
    1 []
    

提交回复
热议问题