Skip to content

Commit dce2d34

Browse files
committed
section on instatiation vs assignment
1 parent 5ec4d80 commit dce2d34

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

doc/source/3_objects.rst

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -798,6 +798,68 @@ creating single objects representing high level mathematical
798798
abstractions whose concrete realisation in code may require many
799799
pieces of data and a large number of complex functions.
800800

801+
Assignment and instantiation
802+
----------------------------
803+
804+
One common confusion among new Python programmers concerns the distinction
805+
between making new objects, and assigning new names to existing objects. The
806+
key point to remember is that assignment in Python does not by itself create
807+
new objects, only new variable names. For example:
808+
809+
.. code-block:: ipython3
810+
811+
In [1]: a = set()
812+
813+
In [2]: b = a
814+
815+
The right hand side of the first line :term:`instantiates <instantiate>` a new
816+
set, and the assignment creates the name `a` and associates it with the same
817+
set. The second line is just an assignment: it associates the name `b` with the
818+
same set. We can see the effect of this if we add an item to `b` and then look
819+
at the contents of `a`:
820+
821+
.. code-block:: ipython3
822+
823+
In [3]: b.add(1)
824+
825+
In [4]: print(a)
826+
{1}
827+
828+
The same distinction between instantiating objects and making new references to
829+
them is the cause of a frequent mistake when trying to create a list of empty
830+
objects:
831+
832+
.. code-block:: ipython3
833+
834+
In [5]: c = [set()] * 5
835+
836+
In [6]: print(c)
837+
[set(), set(), set(), set(), set()]
838+
839+
The programmer almost certainly intended to create a list containing five empty
840+
sets. Instead, they have created a list containing five references to the same
841+
set:
842+
843+
.. code-block:: ipython3
844+
845+
In [7]: c[0].add(2)
846+
847+
In [8]: print(c)
848+
[{2}, {2}, {2}, {2}, {2}]
849+
850+
The right way to create a list of five empty sets is to use a list
851+
comprehension. This will instantiate a different set for each entry in the
852+
list:
853+
854+
.. code-block:: ipython3
855+
856+
In [9]: d = [set() for i in range(5)]
857+
858+
In [10]: d[0].add(2)
859+
860+
In [11]: print(d)
861+
[{2}, set(), set(), set(), set()]
862+
801863
Glossary
802864
--------
803865

0 commit comments

Comments
 (0)