For-each behavior while modifying a collection

Chris Angelico rosuav at gmail.com
Fri Nov 29 04:47:53 EST 2013


On Fri, Nov 29, 2013 at 9:14 AM, Valentin Zahnd <v.zahnd at gmail.com> wrote:
>      def keepByValue(self, key=None, value=[]):
>          tmpFlows = []
>          while len(self.flows) > 0:
>              row = self.flows.pop()
>              if row[key] in value:
>                  tmpFlows.append(row)
>          self.flows = tmpFlows

This is almost certainly going to be less efficient than the
comprehension - it churns the length of the list terribly. There's
very little duplication, as the actual _contents_ will not be
duplicated, only references to them; so the list comp is both clean
and efficient.

More importantly, the way you write a Python program should be:

1) Make it work and look clean.
2) See if it's fast enough. If so - and it usually will be - you're done.
3) Profile it and find out where the slow bits really are.
4) Try to speed up some of the slow bits.

You'll seldom get past step 2. The difference between "fast" and "fast
enough" is usually not visible to a human.

ChrisA



More information about the Python-list mailing list