I couldn't find an explanation for the code in python doc article 4.2 regarding the for loop.
It mentioned something like: if we don't make a copy of the list, then it will print infinite list values for the list words = ['cat', 'window', 'defenestrate']
; but not if we make a copy of it beforehand using "for w in words[:]"
. I need an explanation for this.
words = ['cat', 'window', 'defenestrate']
for w in words :
if len(w) > 6:
words.insert(0,w)
This code will run in an infinite loop, but not if we swap the for w in
wordswith
for w in words[:]`
With [:]
you create a copy of the list content at that moment, and that would be:
words = ['cat', 'window', 'defenestrate'] # equals words[:]
for i, w in enumerate(words[:]):
print(i, w)
if len(w) > 6:
words.insert(0,w)
print("len:", len(words))
#0 cat
#1 window
#2 defenestrate
#len: 4
But using the words
variable itself, stepping your loop does nothing as your step forward is annulled with the insertion at the first position:
words = ['cat', 'window', 'defenestrate']
for i, w in enumerate(words):
print(i, w)
if len(w) > 6:
words.insert(0,w)
print("len:", len(words))
#0 cat
#1 window
#2 defenestrate
#len: 4
#3 defenestrate
#len: 5
#4 defenestrate
#len: 6
#5 defenestrate
#len: 7
#6 defenestrate
#len: 8
#7 defenestrate
#len: 9
#...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With