Collecting Python insights

July 3rd, 2008 at 7:09 pm

I’ve started collecting random insights on Python here. The goal is a single place, accessible online, where I can find answers on topics I’ve struggled with before.

I hope others will find the page helpful as well. If you have comments, leave them here.

Related posts:

  1. Python insights
  2. libcollect - collecting Python distributions
  3. matplotlib - plotting with Python

8 Responses to “Collecting Python insights”

  1. JBNo Gravatar Says:

    xrange uses less memory, but it is slightly slower, as it needs to generate each value on demand.

    Just sayin’.

  2. Mahadevan RNo Gravatar Says:

    In RandomChunker.chunk(), instead of “return ret”, do “yield ret”. Then, you can:

    for chunk in rc.chunk():
    print chunk

    Cheers,
    -Mahadevan.

  3. elibenNo Gravatar Says:

    JB:

    As this benchmark demonstrates, you are quite wrong. xrange is faster (tried for both large and small LISTSIZE):

    import timeit
    
    setup = “”"
    LISTSIZE = 10
    “”"
    
    s1 = “”"
    k = 0
    for i in range(LISTSIZE): k += i
    “”"
    
    s2 = “”"
    k = 0
    for i in xrange(LISTSIZE): k += i
    “”"
    
    N = 50000
    print “range on integer”, timeit.Timer(stmt=s1, setup=setup).timeit(N)
    print “xrange on integer”, timeit.Timer(stmt=s2, setup=setup).timeit(N)
    
  4. elibenNo Gravatar Says:

    Mahadevan R:

    The “insights” supposes RandomChunk already exists and can’t be modified.

  5. alainNo Gravatar Says:

    Python doesn’t have a reverse builtin but it has a reversed builtin:
    for char in reversed(”hello world”):
    print char

  6. ScrewtapeNo Gravatar Says:

    The example for ‘Dynamic code evaluation’ is a good example of how to use exec, but a bad example of when exec is appropriate.The following code is a much nicer way of achieving the same thing, because it doesn’t involve exec and hence you never have to worry about people feeding it malicious strings:

    def make_packet_extract(a, b):
    ____def foo(packet):
    ________return ord(packet[a]) + 256 * ord(packet[b])
    ____return foo

    (apologies for the underscores, <pre> didn’t seem to want to do its thing)

    A better example for exec might be something where you have to change the actual structure of the method you’re building rather than just values within it - changing ‘and’ to ‘or’ or similar.

  7. IvanNo Gravatar Says:

    Function reverse won’t work for UTF8 strings

  8. PabloNo Gravatar Says:

    defaultdict(int) is faster than defaultdict(lambda: 0)

Leave a Reply

You can use these HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .
To post code with preserved formatting, enclose it in `backticks` (even multiple lines)