Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In python why do lists use "+" and dictionaries use "|" to achieve the same thing?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> [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?

>Solution :

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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading