and vs. &

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

Conclusion:

  • 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'
  • Between two integers, & servers as a bitwise operator. If interested, see this page.

Leave a Reply

Your email address will not be published.

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL and press the [Ping me!] button down there. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again.