@@ -405,13 +405,6 @@ indexed and sliced::
405
405
>>> squares[-3:] # slicing returns a new list
406
406
[9, 16, 25]
407
407
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
-
415
408
Lists also support operations like concatenation::
416
409
417
410
>>> squares + [36, 49, 64, 81, 100]
@@ -435,6 +428,30 @@ the :meth:`!list.append` *method* (we will see more about methods later)::
435
428
>>> cubes
436
429
[1, 8, 27, 64, 125, 216, 343]
437
430
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
+
438
455
Assignment to slices is also possible, and this can even change the size of the
439
456
list or clear it entirely::
440
457
0 commit comments