Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Why not just:

    def f(list): 
        return ''.join([chr(l) for l in list])


Because it's an old article. Admittedly, there's no easy way to know this, because it has no date, but believe me, it's been around for ages. At the very least, it predates the silly str.join method (and new-style classes and string methods altogether).

However, before that, there was the string module, which had the join() function. This article probably relates to it in some way; I think that either it predates string.join (I'm not sure when that was added to Python, but it's been around since at least 1.4), or it clarifies how it was implemented.

The author is Guido van Rossum, by the way (another thing that isn't mentioned in the article).


WTF, Guido wrote that!? I will jump out of a window now.


It is actually slower. Adding an f8 function using the ''.join() method:

  sikanda-13:30:02:/tmp$ python f.py 
  [...]
  f1 0.07
  f2 0.12
  f3 0.07
  f4 0.06
  f5 0.09
  f6 0.04
  f7 0.02
  f8 0.07
Original code linked in the article: http://www.python.org/doc/essays/f.py


My results agree with yours, in terms of who wins. Python 2.6 (2.4 is similar, and 3.0 is as well, for the techniques that were still valid) on OSX 10.5, Intel Core Duo at 2 GHz:

  [scotts@silver]$ /opt/local/bin/python2.6 f.py
  f1 0.107
  f2 0.19
  f3 0.106
  f4 0.097
  f5 0.139
  f6 0.073
  f7 0.025
  f8 0.103
edit: I added a ninth function,

  def f9(list):
    return ''.join(map(chr, list))
To test if the difference between f8 and f6 was the list comprehension or the joinfields method. A result of 0.072 tells me it's the list comprehension. The only difference between f8 and f9 is list comprehension versus map. That leads me to conclude that map is indeed a faster way to construct a list than a list comprehension. (Although this may change for a user-defined function. I could test this, but I've spent enough time already.)


This would be my default approach as well. I'd be interested to see how it compares-- my guess is that it would be equivalent to or slightly faster than f6(), and slower than the version that uses the array library.


Actually, map is still faster:

    In [24]: timeit ''.join(map(chr, ll))
    100000 loops, best of 3: 3.91 us per loop

    In [25]: timeit ''.join([chr(i) for i in ll])
    100000 loops, best of 3: 5.85 us per loop

    In [26]: timeit ''.join(chr(i) for i in ll)
    100000 loops, best of 3: 7.79 us per loop


From the article, I'm guessing the author was using a version <2.x.

Incidentally, I ran my function and f6 from the article on a list of 9600 integers using Python 2.6.3. f6 ran in 0.00303250832159 seconds and my function ran in 0.00421450212248 seconds.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: