Skip to content

[3.11] GH-116271 Docs: provide clarification for object assignments in the Tutorial section (GH-116283) #116306

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions Doc/tutorial/introduction.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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::

Expand Down