How smart is the Python interpreter?

Ulrich Eckhardt eckhardt at satorlaser.com
Thu Jul 31 07:30:21 EDT 2008


ssecorp wrote:
> def str_sort(string):
>   s = ""
>   for a in sorted(string):
>     s+=a
>   return s
> 
> 
> if i instead do:
> 
> def str_sort(string):
>   s = ""
>   so = sorted(string)
>   for a in so:
>     s+=a
>   return s
> 
> will that be faster or the interpreter can figure out that it only has
> to do sorted(string) once?

Actually, by replacing sorted() with a function that outputs when it is
called you could have seen that this is only called once in both cases. It
must not be called more than once in fact, consider e.g. the case that it
introduces side effects (like e.g. reading a file).

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list