This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Tutorial: 4.2. for Statements
Type: compile error Stage: resolved
Components: Documentation Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: docs@python Nosy List: Derangedn00b, docs@python
Priority: normal Keywords:

Created on 2019-09-08 16:13 by Derangedn00b, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (1)
msg351331 - (view) Author: Kevin (Derangedn00b) Date: 2019-09-08 16:13
>>> # 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
History
Date User Action Args
2022-04-11 14:59:19adminsetgithub: 82239
2019-09-08 16:17:16Derangedn00bsetstatus: open -> closed
resolution: not a bug
stage: resolved
2019-09-08 16:13:34Derangedn00bcreate