6

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 python? I assume that they should be similar?

dict1 ={"city":"","name":"yass","region":"","zipcode":"",
   "phone":"","address":"","tehsil":"", "planet":"mars"}

whitelist = {"name", "phone", "zipcode", "region", "city",
             "munic", "address", "subarea"}

result = {k: dict1[k] for k in dict1.viewkeys() & whitelist if dict1[k]}
3
  • This isn't a duplicate, the question is also referring to set operations
    – jamylak
    May 22, 2013 at 15:45
  • 3
    @jamylak The set part of the question was added as an edit after I voted close. May 22, 2013 at 15:46
  • Yes. I am writing about that. was getting keyerror when I user "and" instead of '&'
    – hjelpmig
    May 22, 2013 at 15:46

5 Answers 5

10

and is a logical operator which is used to compare two values, IE:

> 2 > 1 and 2 > 3
True

& is a bitwise operator that is used to perform a bitwise AND operation:

> 255 & 1
1

Update

With respect to set operations, the & operator is equivalent to the intersection() operation, and creates a new set with elements common to s and t:

>>> a = set([1, 2, 3])
>>> b = set([3, 4, 5])
>>> a & b
set([3])

and is still just a logical comparison function, and will treat a set argument as a non-false value. It will also return the last value if neither of the arguments is False:

>>> a and b
set([3, 4, 5])
>>> a and b and True
True
>>> False and a and b and True
False

For what its worth, note also that according to the python docs for Dictionary view objects, the object returned by dict1.viewkeys() is a view object that is "set-like":

The objects returned by dict.viewkeys(), dict.viewvalues() and dict.viewitems() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

...

dictview & other

Return the intersection of the dictview and the other object as a new set.

...

3
  • 2
    you should use set not Set
    – tacaswell
    May 22, 2013 at 15:54
  • Good catch, thanks. From the docs: The built-in set and frozenset types were designed based on lessons learned from the sets module. May 22, 2013 at 15:56
  • & isn't completely bitwise. For example, you can't use it to compare floats, or a float with a NaN. Feb 7, 2018 at 19:47
7
  • 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)

3

Yes and is a logical and whereas & is a bitwise and. See example -

>>> 1 and 2
2
>>> 1 & 2
0

The first result is due to short circuiting. Python tests 1 and finds it true and returns the 2. But, the second part does 01 (Binary 1) & 10 (Binary 2) hence evaluating to 00 (1 & 0, 0 &1) , which is 0.

1

&is the bit-wise and operator, and is the boolean logic operator. They're quite different, don't confuse them! For example:

7 & 3
=> 3

True and False
=> False
1
  • Note: this answer was posted before OP modified the question, indicating that the operators were to be applied on sets May 22, 2013 at 20:00
1
>>> help('&')

+-------------------------------------------------+---------------------------------------+
| Operator                                        | Description                           |
+=================================================+=======================================+
| ``lambda``                                      | Lambda expression                     |
+-------------------------------------------------+---------------------------------------+
| ``if`` -- ``else``                              | Conditional expression                |
+-------------------------------------------------+---------------------------------------+
| ``or``                                          | Boolean OR                            |
+-------------------------------------------------+---------------------------------------+
| ``and``                                         | Boolean AND                           |
+-------------------------------------------------+---------------------------------------+
| ``not`` ``x``                                   | Boolean NOT                           |
+-------------------------------------------------+---------------------------------------+
| ``in``, ``not in``, ``is``, ``is not``, ``<``,  | Comparisons, including membership     |
| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==``   | tests and identity tests,             |
+-------------------------------------------------+---------------------------------------+
| ``|``                                           | Bitwise OR                            |
+-------------------------------------------------+---------------------------------------+
| ``^``                                           | Bitwise XOR                           |
+-------------------------------------------------+---------------------------------------+
| ``&``                                           | Bitwise AND                           |
+-------------------------------------------------+---------------------------------------+
| ``<<``, ``>>``                                  | Shifts                                |
+-------------------------------------------------+---------------------------------------+
| ``+``, ``-``                                    | Addition and subtraction              |
+-------------------------------------------------+---------------------------------------+
| ``*``, ``/``, ``//``, ``%``                     | Multiplication, division, remainder   |
|                                                 | [8]                                   |
+-------------------------------------------------+---------------------------------------+
| ``+x``, ``-x``, ``~x``                          | Positive, negative, bitwise NOT       |
+-------------------------------------------------+---------------------------------------+
| ``**``                                          | Exponentiation [9]                    |
+-------------------------------------------------+---------------------------------------+
| ``x[index]``, ``x[index:index]``,               | Subscription, slicing, call,          |
| ``x(arguments...)``, ``x.attribute``            | attribute reference                   |
+-------------------------------------------------+---------------------------------------+
| ``(expressions...)``, ``[expressions...]``,     | Binding or tuple display, list        |
| ``{key: value...}``, ```expressions...```       | display, dictionary display, string   |
|                                                 | conversion                            |
+-------------------------------------------------+---------------------------------------+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.