[New-bugs-announce] [issue38058] Tutorial: 4.2. for Statements
Kevin
report at bugs.python.org
Sun Sep 8 12:13:34 EDT 2019
New submission from Kevin <Kfbritton at gmail.com>:
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
>>>>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
words is a tuple and is immutable
----------
assignee: docs at python
components: Documentation
messages: 351331
nosy: Derangedn00b, docs at python
priority: normal
severity: normal
status: open
title: Tutorial: 4.2. for Statements
type: compile error
versions: Python 3.7
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue38058>
_______________________________________
More information about the New-bugs-announce
mailing list