Home > Software design >  In python why do lists use " " and dictionaries use "|" to achieve the same thin
In python why do lists use " " and dictionaries use "|" to achieve the same thin

Time:11-23

In python, to add two lists together, we use " ":

>>> [0, 1]   [2, 3]
[0, 1, 2, 3]

and for dictionaries we use "|":

>>> {'a': 0, 'b': 1} | {'c': 2, 'd': 3}
{'a': 0, 'b': 1, 'c': 2, 'd': 3}

however, don't these two operations achieve the same thing? In that case, why do they use two different operators, especially when both lists and dictionaries don't support the use of "|" and " " respectively?

>>> [0, 1] | [2, 3]
TypeError: unsupported operand type(s) for |: 'list' and 'list'
>>> {'a': 0, 'b': 1}   {'c': 2, 'd': 3}
TypeError: unsupported operand type(s) for  : 'dict' and 'dict'

Wouldn't it make more sense for dictionaries to support " " to achieve what "|" is used for?

CodePudding user response:

When you use list list you are adding the two lists in the sense that the resulting list will always have all the elements of the first two lists:

[1, 2]   [2]  ->  [1, 2, 2]

But dictionaries can only contain one of each key, so when you use dict | dict not all the values will be in the resulting dictionary if both starting dictionaries had the same key:

{"a": 1, "b": 2} | {"a": 3}  ->  {"a": 3, "b": 2}

The keys of the dictionary are not repeated even if they are there in both original dictionaries and therefore mathematically, the result is not the addition of the two dictionaries but instead the union. The symbol | is used to represent this.

Note that the same goes for other types as well - the is used when the same key / value can be repeated twice but the | is used whenever it cannot.

[1, 2]   [2]  # [1, 2, 2]
(1, 2)   (2,)  # (1, 2, 2)
{"a": 1, "b": 2} | {"b": 3}  # {"a": 1, "b": 3}
{1, 2} | {2, 3}  # {1, 2, 3}
  • Related