summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2024-03-04 12:28:43 (GMT)
committerGitHub <noreply@github.com>2024-03-04 12:28:43 (GMT)
commitf6de98407d6bbd363d23cca77082ab3d99496516 (patch)
tree72f28b8da1594b2b0c1f667c1f6f2fae4adf4900
parenteb0603b855bb3928f34e3bff391e3a40fab95265 (diff)
downloadcpython-f6de98407d6bbd363d23cca77082ab3d99496516.zip
cpython-f6de98407d6bbd363d23cca77082ab3d99496516.tar.gz
cpython-f6de98407d6bbd363d23cca77082ab3d99496516.tar.bz2
[3.12] GH-116271 Docs: provide clarification for object assignments in the Tutorial section (GH-116283) (#116305)
Co-authored-by: Kerim Kabirov <39376984+Privat33r-dev@users.noreply.github.com> 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::