[Python-checkins] cpython (3.5): Improve tutorial suggestion for looping techniques
raymond.hettinger
python-checkins at python.org
Tue Sep 1 11:33:28 CEST 2015
https://hg.python.org/cpython/rev/447d8e6b17b9
changeset: 97564:447d8e6b17b9
branch: 3.5
parent: 97561:833db9e2ed14
user: Raymond Hettinger <python at rcn.com>
date: Tue Sep 01 02:33:02 2015 -0700
summary:
Improve tutorial suggestion for looping techniques
files:
Doc/tutorial/datastructures.rst | 20 ++++++++++----------
1 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -612,18 +612,18 @@
orange
pear
-To change a sequence you are iterating over while inside the loop (for
-example to duplicate certain items), it is recommended that you first make
-a copy. Looping over a sequence does not implicitly make a copy. The slice
-notation makes this especially convenient::
+It is sometimes tempting to change a list while you are looping over it;
+however, it is often simpler and safer to create a new list instead. ::
- >>> words = ['cat', 'window', 'defenestrate']
- >>> for w in words[:]: # Loop over a slice copy of the entire list.
- ... if len(w) > 6:
- ... words.insert(0, w)
+ >>> import math
+ >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
+ >>> filtered_data = []
+ >>> for value in raw_data:
+ ... if not math.isnan(value):
+ ... filtered_data.append(value)
...
- >>> words
- ['defenestrate', 'cat', 'window', 'defenestrate']
+ >>> filtered_data
+ [56.2, 51.7, 55.3, 52.5, 47.8]
.. _tut-conditions:
--
Repository URL: https://hg.python.org/cpython
More information about the Python-checkins
mailing list