title: Python 3: Removing list item with for loop, is this the right way?
body: <p>I am still learning the basics of python, and I have just spent a while reading about how to remove an item from a list in python from within a for loop. Everything I've read suggests complex ways of doing this, and they say that you cannot remove an item from a list while you're iterating over it. However... this seems to work:</p>
  
  <pre><code>class Object():
      def __init__(self):
          self.y = 0
  
  object_list = [Object(), Object(), Object()]
  
  for thing in object_list:
      thing.y += 1
      if thing.y &gt; 10:
          object_list.remove(thing)
  </code></pre>
  
  <p>Why is this working when others say it isn't and write complicated workarounds? Is it because you aren't allowed to do it in Python 2 but can in Python 3?</p>
  
  <p>And is this the right way to do this? Will it work as I want it or will it be prone to bugs? Would it be advisable to iterate over the list in reverse order if I plan to remove items?</p>
  
  <p>Sorry if this has been answered before, but it's hard to know which resources refer to what as they all just say "python" in the tag (at least, the ones I've been reading, maybe that's because all the ones I have read are python 2?)</p>
  
  <p>Thanks!</p>
  
  <p>EDIT:</p>
  
  <p>Sorry, there were a couple of copy and paste errors... I've fixed them...</p>
  
  <p>EDIT:</p>
  
  <p>I've been watching another one of Raymond Hettinger's videos... He mentions a way of removing items from a dictionary while iterating over it by using dict.keys(). Something like:</p>
  
  <pre><code>d = {'text': 'moreText', 'other': 'otherText', 'blah': 'moreBlah'}
  
  for k in d.keys():
      if k.startswith('o'):
          del d[k]
  </code></pre>
  
  <p>Apparently using the keys makes it safe to remove the item while iterating. Is there an equivalent for lists? If there was I could iterate backwards over the list and remove items safely</p>