diff options
author | Raymond Hettinger <python@rcn.com> | 2015-09-01 02:33:02 -0700 |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2015-09-01 02:33:02 -0700 |
commit | 70e7ee2e4fcc9672b595ad9f4d35094f3cf207da (patch) | |
tree | b7a2ccff00939dd2d5f414169e9a83925d723724 /Doc/tutorial/datastructures.rst | |
parent | 49f5b2879fe463018726921604b683e6bd72bf39 (diff) | |
download | cpython-70e7ee2e4fcc9672b595ad9f4d35094f3cf207da.tar.gz |
Improve tutorial suggestion for looping techniques
Diffstat (limited to 'Doc/tutorial/datastructures.rst')
-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 a2031ed867..0d51480177 100644 --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -612,18 +612,18 @@ returns a new sorted list while leaving the source unaltered. :: 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:: - - >>> 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: |