diff options
author | Raymond Hettinger <python@rcn.com> | 2015-09-01 09:20:44 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2015-09-01 09:20:44 (GMT) |
commit | 9ce9f779835b13a8a1a430374135ee28ae956c4f (patch) | |
tree | 92af26dbb413ed4fe47f064a60152f05f149fdc4 /Doc | |
parent | 6a31bb5cac8729a4bc65909fee496c18af903655 (diff) | |
download | cpython-9ce9f779835b13a8a1a430374135ee28ae956c4f.zip cpython-9ce9f779835b13a8a1a430374135ee28ae956c4f.tar.gz cpython-9ce9f779835b13a8a1a430374135ee28ae956c4f.tar.bz2 |
Improve tutorial suggestion for looping techniques
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/tutorial/datastructures.rst | 22 |
1 files changed, 11 insertions, 11 deletions
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst index 89589bc..48faa9c 100644 --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -664,18 +664,18 @@ retrieved at the same time using the :meth:`iteritems` method. :: gallahad the pure robin the brave -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:: - - >>> 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) +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. :: + + >>> 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: |