I don't understand what the 0 in insert(0, w) is doing. When I change it with another number the output stays the same.
>>> for w in words[:]: # Loop over a slice copy of the entire list.
... if len(w) > 6:
... words.insert(0, w)
...
I've encountered this issue with python tutorial before, and here is my explanation.
Let's step back and look at the context:
This example is from Chapter 4 of the python Tutorial, but the line of code you are questioning references Chapter 5.1 of the same Tutorial.
The 'insert' method on lists is here:
https://docs.python.org/2.7/tutorial/datastructures.html
The confusion is understandable if you are doing the Tutorial 'in order', which, of course, you should be, then you are unfamiliar with that line of code. Jump ahead to chapter 5.1, and see this:
list.insert(i, x) Insert an item at a given position. The first
argument is the index of the element before which to insert, so
a.insert(0, x) inserts at the front of the list, and a.insert(len(a),
x) is equivalent to a.append(x).
The point the author is trying to show is that you want to make a copy of the list before modifying the list inside a loop, or 'bad things'™ can happen.
See: Thou Shalt Not Modify A List During Iteration
If you don't copy the list, the loop never finishes... try this:
>>> for w in words: # Loop over the list, and modify it while looping
... if len(w) > 6:
... words.insert(0, w)
...
You will be waiting until you run out of memory, but you are getting this:
['defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'defenestrate', 'cat', 'window', 'defenestrate']
The reason is this:
- for loop gets 'w' from
words[0]: 'cat'
len('cat') > 6 is false - continue
- for loop gets 'w' from
words[1]: 'window'
len('window') > 6 is false - continue
- for loop gets 'w' from
words[2]: 'defenestrate'
len('defenstrate') > 6 is true
- insert...
words is now ['defenestrate', 'cat', 'window', 'defenestrate']
- for loop gets 'w' from
words[3]: 'defenstrate'
len('defenstrate') > 6 is true
- insert...
words is now ['defenstrate, 'defenestrate', 'cat', 'window', 'defenestrate']
- for loop gets 'w' from
words[4]: 'defenstrate'
... continues for infinity.
when you copy the list, this happens:
- for loop gets 'w' from THE COPY OF
words[3]
- raise Exception: IndexError (because THE COPY OF
words is only 3 items long)
- for loop handles exception by terminating loop.
You never altered the copy of the 'words' list.
You are altering the original 'words' list.
The copy is anonymous. It's a variable only used to control the loop, and only available internal to the loop. It goes away when the loop terminates.