3

Is there any difference in the logic or performance of using the word and vs. the & symbol in Python?

Nayuki
  • 17,911
  • 6
  • 53
  • 80
Alex
  • 2,154
  • 3
  • 26
  • 49
  • 5
    This appears to be a duplicate of [this question](http://stackoverflow.com/q/22646463/4873159) – Burgan Oct 05 '15 at 04:06
  • Try `1 and 1 and 2` and `1 & 1 & 2` – Remi Guan Oct 05 '15 at 04:09
  • 2
    @FlashDrive Your linked question is related but too long. It gets into too much into numpy and lists. The question here is simple and deserves a simple answer. – Nayuki Oct 05 '15 at 04:18
  • So I don't think the linked question is a good reference for a duplicate. But if there is a more straightforward Q&A on this topic, then I will concede to that one instead as the duplicate. – Nayuki Oct 05 '15 at 04:19
  • I'm not clear on what I'm supposed to do with this question. Should I erase it because it has a lot of overlap with the question @FlashDrive cited? – Alex Oct 05 '15 at 12:16
  • @Alex I think your question is a good question. Please let it stand. – Nayuki Oct 05 '15 at 23:41

1 Answers1

8

and is a Boolean operator. It treats both arguments as Boolean values, returning the first if it's falsy, otherwise the second. Note that if the first is falsy, then the second argument isn't even computed at all, which is important for avoiding side effects.

Examples:

  • False and True --> False
  • True and True --> True
  • 1 and 2 --> 2
  • False and None.explode() --> False (no exception)

& has two behaviors.

  • If both are int, then it computes the bitwise AND of both numbers, returning an int. If one is int and one is bool, then the bool value is coerced to int (as 0 or 1) and the same logic applies.
  • Else if both are bool, then both arguments are evaluated and a bool is returned.
  • Otherwise a TypeError is raised (such as float & float, etc.).

Examples:

  • 1 & 2 --> 0
  • 1 & True --> 1 & 1 --> 1
  • True & 2 --> 1 & 2 --> 0
  • True & True --> True
  • False & None.explode() --> AttributeError: 'NoneType' object has no attribute 'explode'
Nayuki
  • 17,911
  • 6
  • 53
  • 80