summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKerim Kabirov <39376984+Privat33r-dev@users.noreply.github.com>2024-03-04 12:22:13 (GMT)
committerGitHub <noreply@github.com>2024-03-04 12:22:13 (GMT)
commit45a92436c5c42ca100f3ea0de9e7d37f1a97439b (patch)
tree0095f1db219f58af5bb4f5b9162635ec75625134
parenteda2963378a3c292cf6bb202bb00e94e46ee6d90 (diff)
downloadcpython-45a92436c5c42ca100f3ea0de9e7d37f1a97439b.zip
cpython-45a92436c5c42ca100f3ea0de9e7d37f1a97439b.tar.gz
cpython-45a92436c5c42ca100f3ea0de9e7d37f1a97439b.tar.bz2
GH-116271 Docs: provide clarification for object assignments in the Tutorial section (#116283)
Co-authored-by: Ned Batchelder <ned@nedbatchelder.com> Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
-rw-r--r--Doc/tutorial/introduction.rst31
1 files changed, 24 insertions, 7 deletions
diff --git a/Doc/tutorial/introduction.rst b/Doc/tutorial/introduction.rst
index 4536ab9..0f16dae 100644
--- a/Doc/tutorial/introduction.rst
+++ b/Doc/tutorial/introduction.rst
@@ -405,13 +405,6 @@ indexed and sliced::
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]
-All slice operations return a new list containing the requested elements. This
-means that the following slice returns a
-:ref:`shallow copy <shallow_vs_deep_copy>` of the list::
-
- >>> squares[:]
- [1, 4, 9, 16, 25]
-
Lists also support operations like concatenation::
>>> squares + [36, 49, 64, 81, 100]
@@ -435,6 +428,30 @@ the :meth:`!list.append` *method* (we will see more about methods later)::
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
+Simple assignment in Python never copies data. When you assign a list
+to a variable, the variable refers to the *existing list*.
+Any changes you make to the list through one variable will be seen
+through all other variables that refer to it.::
+
+ >>> rgb = ["Red", "Green", "Blue"]
+ >>> rgba = rgb
+ >>> id(rgb) == id(rgba) # they reference the same object
+ True
+ >>> rgba.append("Alph")
+ >>> rgb
+ ["Red", "Green", "Blue", "Alph"]
+
+All slice operations return a new list containing the requested elements. This
+means that the following slice returns a
+:ref:`shallow copy <shallow_vs_deep_copy>` of the list::
+
+ >>> correct_rgba = rgba[:]
+ >>> correct_rgba[-1] = "Alpha"
+ >>> correct_rgba
+ ["Red", "Green", "Blue", "Alpha"]
+ >>> rgba
+ ["Red", "Green", "Blue", "Alph"]
+
Assignment to slices is also possible, and this can even change the size of the
list or clear it entirely::