Jason Shew

and v.s. &

Published
Sun ⋆ 2022-06-12 ⋆ 19:43 EDT

When texting people or posting a status on social media, we often write the word and as & (ampersand) for convenience. But does Python handle and and & the same way?

str1 = "Apple"
a = ("p" in str1) & ("l" in str1)
b = "p" in str1 and "l" in str1
print(a == b)
print(a is b)

OUTPUT
True
True

It’s obvious that Python treats and and & the same way as a logical operator. How about using them between sets?

set1 = {0,1,2,3,4,5}
set2 = {4,5,6,7,8,9}
d = set1.intersection(set2)
e = set1 & set2
f = set1 and set2
g = set2 and set1
print(d == e)
print(e == f)
print(f == g)

OUTPUT
True
False
False

Dang! It seems that set1 & set2, which is equivalent to set1.intersection(set2), is not the same thing as set1 and set2. Even set1 and set2 and set2 and set1 are different things. Why?

If we look closer, we may find:

print(f == set2)
print(g == set1)
print(f is set2)
print(g is set1)
OUTPUT
True
True
True
True

Roundup:

  1. If you write x and y in Python where x and y are not arithmetic or relational expressions, Python picks up y and dumps x.

  2. If you write x & y in Python where x and y are not arithmetic or relational expressions, Python mostly won’t recognize it unless x and y are two sets.

  3. While ("p" in str1) & ("l" in str1) and "p" in str1 and "l" in str1 are the same expression, be careful with the parentheses since "p" in str1 & "l" in str1 will result in a TypeError.

    c = "p" in str1 & "l" in str1

     OUTPUT
     TypeError: unsupported operand type(s) for &: 'str' and 'str'
  4. Between two integers, & servers as a bitwise operator. If interested, see this page.

Next
Bullying Is Not an LGBT Trait – Fri ⋆ 2022-06-17 ⋆ 14:33 EDT
Previous
Addition, Concatenation, and Increment – Sat ⋆ 2022-05-28 ⋆ 04:30 EDT