0

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.

jimfawkes
  • 357
  • 2
  • 12
  • See also [“Removing items from a list while iterating over the list” on sopython.com](https://sopython.com/canon/95/removing-items-from-a-list-while-iterating-over-the-list/) for a concise explanation. – poke Dec 18 '17 at 00:12
  • @poke Thanks for the links. I now understand the behaviour of the initial approach. But why does the second one work? What has changed here? – jimfawkes Dec 18 '17 at 00:24
  • 2
    By creating a copy of the list, you are iterating the *copy*. So when you modify the original list, you do not affect the thing you are actually iterating over. So you basically have two lists: One that you remove the items from, and one that you iterate over. – poke Dec 18 '17 at 00:30
  • Thanks! Its that simple. I guess its late. Have a great day/evening. – jimfawkes Dec 18 '17 at 00:34

0 Answers0