Python Interview Questions

Paul Rubin http
Thu Nov 1 02:06:04 EDT 2007


Rhamphoryncus <rhamph at gmail.com> writes:
> += shouldn't be an obvious choice for sequences.  If it's mutable,
> use .append().  If it's immutable, build up in a mutable sequence,
> then convert.

I generally prefer to do this with generators rather than mutation.
I.e. instead of 

       blech = []
       while some_condition():
          yuck = some mess
          blech.append(yuck)
       result = ''.join(blech)

I like

       def gen_blech():
         while some_condition():
            yield (some mess)
       result = ''.join(gen_blech())

It just seems cleaner.  YMMV.  Of course when "some mess" is a single
expression instead of multiple statements, it may be possible to use
a genexp without the auxiliary function.



More information about the Python-list mailing list