Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9ce9f77

Browse files
committed
Improve tutorial suggestion for looping techniques
1 parent 6a31bb5 commit 9ce9f77

1 file changed

Lines changed: 11 additions & 11 deletions

File tree

Doc/tutorial/datastructures.rst

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -664,18 +664,18 @@ retrieved at the same time using the :meth:`iteritems` method. ::
664664
gallahad the pure
665665
robin the brave
666666

667-
To change a sequence you are iterating over while inside the loop (for
668-
example to duplicate certain items), it is recommended that you first make
669-
a copy. Looping over a sequence does not implicitly make a copy. The slice
670-
notation makes this especially convenient::
671-
672-
>>> words = ['cat', 'window', 'defenestrate']
673-
>>> for w in words[:]: # Loop over a slice copy of the entire list.
674-
... if len(w) > 6:
675-
... words.insert(0, w)
667+
It is sometimes tempting to change a list while you are looping over it;
668+
however, it is often simpler and safer to create a new list instead. ::
669+
670+
>>> import math
671+
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
672+
>>> filtered_data = []
673+
>>> for value in raw_data:
674+
... if not math.isnan(value):
675+
... filtered_data.append(value)
676676
...
677-
>>> words
678-
['defenestrate', 'cat', 'window', 'defenestrate']
677+
>>> filtered_data
678+
[56.2, 51.7, 55.3, 52.5, 47.8]
679679

680680

681681
.. _tut-conditions:

0 commit comments

Comments
 (0)