I want to check if any word is more than once in a list. I wrote the following code:
for word in words:
word = words.pop(0)
try:
index = words.index(word)
if word == words[index]:
return False
except ValueError:
continue
The idea is to remove the first word of the list from the list and check if it exists in the remaining list. However this does not work because the loop will only iterate through the first half of the list.
If I change the first line to the following:
for word in words[:]:
it works as intended. I read about shallow copy in the python docs because it was mentioned in a comment on a SO Question where I found out about the words[:]
approach. However I still don't understand why the first approach is not working and the second one is.
I would love some explanation about the difference of the two versions and if possible some info about how python addresses/references the list in the for-loop.
Edit: poke pointed me to this SO answer which explains the behaviour of the initial approach very nicely.
The thing I did not realize is that the [:] gives me a copy of my list over which I am iterating. Basically I am iterating over the copy but modifying the original list.