Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I happen to stumble upon this code :" With for w in words:, the example would attempt to create an infinite list

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 inwordswithfor w in words[:]`

like image 571
Mayank Jamwal Avatar asked Oct 23 '19 10:10

Mayank Jamwal


1 Answers

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
#...
like image 151
ipaleka Avatar answered Oct 23 '22 04:10

ipaleka