You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/writing/style.rst
+11-18Lines changed: 11 additions & 18 deletions
Original file line number
Diff line number
Diff line change
@@ -606,9 +606,7 @@ Python has standard ways of filtering lists, but there are several things you ne
606
606
Python 2.x vs. 3.x
607
607
::::::::::::::::::
608
608
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
612
610
613
611
.. code-block:: python
614
612
@@ -665,38 +663,33 @@ Modifying the values in a list
665
663
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
666
664
**Bad**:
667
665
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
+
668
668
.. code-block:: python
669
669
670
670
# Add three to all list members.
671
671
a = [3, 4, 5]
672
+
b = a # a and b refer to the same list object
673
+
672
674
for i inrange(len(a)):
673
-
a[i] +=3
675
+
a[i] +=3# b[i] also changes
674
676
675
677
**Good**:
676
678
679
+
It's safer to create a new list object and leave the original alone.
680
+
677
681
.. code-block:: python
678
682
679
683
a = [3, 4, 5]
684
+
b = a
685
+
686
+
# assign the variable "a" to a new list without changing "b"
680
687
a = [i +3for i in a]
681
688
# Or (Python 2.x):
682
689
a =map(lambdai: i +3, a)
683
690
# Or (Python 3.x)
684
691
a =list(map(lambdai: i +3, a))
685
692
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 +3for i in a]
695
-
# Or (Python 2.x):
696
-
b =map(lambdai: i +3, a)
697
-
# Or (Python 3.x)
698
-
b =list(map(lambdai: i +3, a))
699
-
700
693
701
694
Use :py:func:`enumerate` keep a count of your place in the list.
0 commit comments