Skip to content

Commit 29abc5a

Browse files
authored
Modifying the values in a list
To avoid side effects, don't modify the original list. Create a new list instead.
1 parent e69d7e7 commit 29abc5a

File tree

1 file changed

+11
-18
lines changed

1 file changed

+11
-18
lines changed

docs/writing/style.rst

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -606,9 +606,7 @@ Python has standard ways of filtering lists, but there are several things you ne
606606
Python 2.x vs. 3.x
607607
::::::::::::::::::
608608

609-
* Starting with Python 3.0, the :py:func:`map` and :py:func:`filter`
610-
functions return an iterator instead of a list. If you really need a list, you
611-
should wrap these functions in :py:func`list` like so
609+
* Starting with Python 3.0, the :py:func:`map` and :py:func:`filter` functions return an iterator instead of a list. If you really need a list, you should wrap these functions in :py:func`list` like so
612610

613611
.. code-block:: python
614612
@@ -665,38 +663,33 @@ Modifying the values in a list
665663
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
666664
**Bad**:
667665

666+
Remember that assignment never creates a new object. If 2 or more variables refer to the same list, changing one of them changes them all.
667+
668668
.. code-block:: python
669669
670670
# Add three to all list members.
671671
a = [3, 4, 5]
672+
b = a # a and b refer to the same list object
673+
672674
for i in range(len(a)):
673-
a[i] += 3
675+
a[i] += 3 # b[i] also changes
674676
675677
**Good**:
676678

679+
It's safer to create a new list object and leave the original alone.
680+
677681
.. code-block:: python
678682
679683
a = [3, 4, 5]
684+
b = a
685+
686+
# assign the variable "a" to a new list without changing "b"
680687
a = [i + 3 for i in a]
681688
# Or (Python 2.x):
682689
a = map(lambda i: i + 3, a)
683690
# Or (Python 3.x)
684691
a = list(map(lambda i: i + 3, a))
685692
686-
**Best**:
687-
688-
Creating a new list instead of modifying the original list will prevent
689-
unexpected side-effects.
690-
691-
.. code-block:: python
692-
693-
a = [3, 4, 5]
694-
b = [i + 3 for i in a]
695-
# Or (Python 2.x):
696-
b = map(lambda i: i + 3, a)
697-
# Or (Python 3.x)
698-
b = list(map(lambda i: i + 3, a))
699-
700693
701694
Use :py:func:`enumerate` keep a count of your place in the list.
702695

0 commit comments

Comments
 (0)