Is there a difference between 'and' and '&' with respect to python sets?

前端 未结 5 542
臣服心动
臣服心动 2020-12-06 13:28

I got very good help for question check if dictionary key has empty value . But I was wondering if there is a difference between and and & in p

5条回答
  •  清歌不尽
    2020-12-06 13:53

    • and is logical and
    • & is bitwise and

    logical and returns the second value if both values evaluate to true.

    For sets & is intersection.

    If you do:

    In [25]: a = {1, 2, 3}
    
    In [26]: b = {3, 4, 5}
    
    In [27]: a and b
    Out[27]: set([3, 4, 5])
    
    In [28]: a & b
    Out[28]: set([3])
    

    This be because bool(a) == True and bool(b) == True so and returns the second set. & returns the intersection of the sets.

    (set doc)

提交回复
热议问题