File tree Expand file tree Collapse file tree 1 file changed +40
-27
lines changed Expand file tree Collapse file tree 1 file changed +40
-27
lines changed Original file line number Diff line number Diff line change @@ -415,39 +415,52 @@ Assignment operator
415
415
416
416
Things to note:
417
417
418
- * a single object can have several names bound to it:
418
+ * A single object can have several names bound to it:
419
419
420
- .. ipython ::
420
+ .. ipython ::
421
+
422
+ In [1]: a = [1, 2, 3]
423
+
424
+ In [2]: b = a
425
+
426
+ In [3]: a
427
+ Out[3]: [1, 2, 3]
421
428
422
- In [1]: a = [1, 2, 3]
423
- In [2]: b = a
424
- In [3]: a
425
- Out[3]: [1, 2, 3]
426
- In [4]: b
427
- Out[4]: [1, 2, 3]
428
- In [5]: a is b
429
- Out[5]: True
430
- In [6]: b[1] = 'hi!'
431
- In [7]: a
432
- Out[7]: [1, 'hi!', 3]
429
+ In [4]: b
430
+ Out[4]: [1, 2, 3]
431
+
432
+ In [5]: a is b
433
+ Out[5]: True
434
+
435
+ In [6]: b[1] = 'hi!'
436
+
437
+ In [7]: a
438
+ Out[7]: [1, 'hi!', 3]
433
439
434
440
* to change a list *in place *, use indexing/slices:
435
441
436
- .. ipython ::
442
+ .. ipython ::
443
+
444
+ In [1]: a = [1, 2, 3]
445
+
446
+ In [3]: a
447
+ Out[3]: [1, 2, 3]
448
+
449
+ In [4]: a = ['a', 'b', 'c'] # Creates another object.
450
+
451
+ In [5]: a
452
+ Out[5]: ['a', 'b', 'c']
453
+
454
+ In [6]: id(a)
455
+ Out[6]: 138641676
456
+
457
+ In [7]: a[:] = [1, 2, 3] # Modifies object in place.
458
+
459
+ In [8]: a
460
+ Out[8]: [1, 2, 3]
437
461
438
- In [1]: a = [1, 2, 3]
439
- In [3]: a
440
- Out[3]: [1, 2, 3]
441
- In [4]: a = ['a', 'b', 'c'] # Creates another object.
442
- In [5]: a
443
- Out[5]: ['a', 'b', 'c']
444
- In [6]: id(a)
445
- Out[6]: 138641676
446
- In [7]: a[:] = [1, 2, 3] # Modifies object in place.
447
- In [8]: a
448
- Out[8]: [1, 2, 3]
449
- In [9]: id(a)
450
- Out[9]: 138641676 # Same as in Out[6], yours will differ...
462
+ In [9]: id(a)
463
+ Out[9]: 138641676 # Same as in Out[6], yours will differ...
451
464
452
465
* the key concept here is **mutable vs. immutable **
453
466
You can’t perform that action at this time.
0 commit comments