1

Possible Duplicate:
Modifying list while iterating

I am writing a python script where I am trying to append objects to a List created in the body of a class, from inside a method.

My code so far is this:

class Worker:

    myList = ['one item', 'second item']

    def itter_List_Func(self, list_param):
       for item in list_param:
           more_items = item.split()
           self.myList[:] = [self.myList + item for item in more_items]

but for a strange kind of fashion I run into some 'Can not modify list while itterated error'. Should I leave the in-place change and try to create a new List object with the new items as well? Or that would create more problems due to lost reference for list_param or something?

3

2 Answers 2

1

To be explicit about the "make a new list directly" idea, you want something like:

myList = sum((item.split() for item in myList), [])

That's the simply-written way, that unfortunately gets slow if you have a lot of items (because sum relies on addition, and addition isn't an efficient way to join lists in Python). Using an explicit loop:

result = []
for item in myList:
    result.extend(item.split())
myList = result

That is: we don't create a copy of the list and try to modify it; we create a blank list and iteratively transform it into what we want, using the original list as input for the process.

By the way, you have two likely design issues here: you seem to be expecting the function to be passed a specific value every time it is called, and you have defined a class attribute where you probably want an instance attribute instead.

1

Ok from the links that avasal provided me with, and some further reading here on stack overflow, I understood that what I am trying to do is a bad idea. Maybe I should try and iterrate over a copy of the original list, or make assignments to a copy of the original list, because, if I make changes to the list while being itterated, the itterators will not be informed about this, resulting in very weird behaviour, or run-time errors.

3
  • 1
    Or you could take a more functional approach and assign myList to a list comprehension which returns the desired elements.
    – jamylak
    Jul 12, 2012 at 10:30
  • @jamylak - Erm, your comment confused me a little bit. Could you explain your comment in a way that is more clear to me? Jul 12, 2012 at 10:39
  • 1
    +1 don't create a copy to try to modify it by making reference to the original list... this gets unbelievably messy surprisingly fast. Instead, make a new list that represents what you want, as-you-go, iterating over the original list for "input". Better yet, do that iteration automatically by using a list comprehension, and simply describing the result in terms of the original, letting Python do the rest. Quit trying to tell Python how to assemble lists. It knows full well how to do so. :) Jul 12, 2012 at 10:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.