Why doesn't join() call str() on its arguments?

Christophe Cavalaria chris.cavalaria at free.fr
Thu Feb 17 15:29:28 EST 2005


Delaney, Timothy C (Timothy) wrote:

> John Roth wrote:
> 
>> result = "".join([str(x) for x in list])
> 
> As of 2.4, you should use a generator expression here instead (unless
> you require backwards-compatibility with 2.3).
> 
>     result = ''.join(str(x) for x in iterable)
> 
> Easier to read, more memory-efficient, potentially faster (depending on
> performance characteristics of building large lists).
> 
> Tim Delaney

Correct me if I'm wrong, but with a real generator expression, join can't
know in advance the final size of the resulting string. So, for big
strings, the fact that you know in advance the size of the list and of the
resulting string could lead to much better performance, even if the memory
usage is twice the one of the generator expression.



More information about the Python-list mailing list