The ,= operator

前端 未结 2 1016
梦毁少年i
梦毁少年i 2021-01-21 06:30

While looking at some Python code I noticed usage of what looked like ,= operator:

a ,= b

After experimentation and very close ins

2条回答
  •  醉话见心
    2021-01-21 06:54

    The statement;

    a, = b
    
    • assumes b is iterable
    • take first value from b and assigns it to a (near to a = b[0])
    • asserts that b has no more values (i.e. len(b) == 1)

    In that sense it is not the same as a = b[0]. The latter would work with b = ['a', 'b'], while the first will raise a ValueError: too many values to unpack. On the other side:

    l = [x]
    it = iter(l)
    a, = it    #fine when a=it[0] raises TypeError: 'listiterator' object has no attribute '__getitem__'
    

    TL/DR: if b is a list or a tuple with one single element, both a, = b and a = b[0] behave the same, but in other cases the may behave differently

提交回复
热议问题