Skip to content

Commit 45a9243

Browse files
Privat33r-devnedbathugovk
authored
GH-116271 Docs: provide clarification for object assignments in the Tutorial section (#116283)
Co-authored-by: Ned Batchelder <[email protected]> Co-authored-by: Hugo van Kemenade <[email protected]>
1 parent eda2963 commit 45a9243

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

Doc/tutorial/introduction.rst

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -405,13 +405,6 @@ indexed and sliced::
405405
>>> squares[-3:] # slicing returns a new list
406406
[9, 16, 25]
407407

408-
All slice operations return a new list containing the requested elements. This
409-
means that the following slice returns a
410-
:ref:`shallow copy <shallow_vs_deep_copy>` of the list::
411-
412-
>>> squares[:]
413-
[1, 4, 9, 16, 25]
414-
415408
Lists also support operations like concatenation::
416409

417410
>>> squares + [36, 49, 64, 81, 100]
@@ -435,6 +428,30 @@ the :meth:`!list.append` *method* (we will see more about methods later)::
435428
>>> cubes
436429
[1, 8, 27, 64, 125, 216, 343]
437430

431+
Simple assignment in Python never copies data. When you assign a list
432+
to a variable, the variable refers to the *existing list*.
433+
Any changes you make to the list through one variable will be seen
434+
through all other variables that refer to it.::
435+
436+
>>> rgb = ["Red", "Green", "Blue"]
437+
>>> rgba = rgb
438+
>>> id(rgb) == id(rgba) # they reference the same object
439+
True
440+
>>> rgba.append("Alph")
441+
>>> rgb
442+
["Red", "Green", "Blue", "Alph"]
443+
444+
All slice operations return a new list containing the requested elements. This
445+
means that the following slice returns a
446+
:ref:`shallow copy <shallow_vs_deep_copy>` of the list::
447+
448+
>>> correct_rgba = rgba[:]
449+
>>> correct_rgba[-1] = "Alpha"
450+
>>> correct_rgba
451+
["Red", "Green", "Blue", "Alpha"]
452+
>>> rgba
453+
["Red", "Green", "Blue", "Alph"]
454+
438455
Assignment to slices is also possible, and this can even change the size of the
439456
list or clear it entirely::
440457

0 commit comments

Comments
 (0)