List Comprehension

Posted: February 21, 2012 in Devops, Featured, Python
Tags: ,

Why is it better to use list comprehension instead of map + lambda?

Take this bit of example code. It generates a random mac address:

random_mac.py

import random

def random_mac(style=3000):
    '''Create a random MAC address'''
    mac = [ random.randint(0x00, 0xff),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff),
            random.randint(0x00, 0xff) ]
    if style == 2000:
        # old style - decrecated
        result = ':'.join(map(lambda x: "%02x" % x, mac))
    else:
        # using list comprehension
        result = ':'.join(['%02x' % m for m in mac])
    return result

Now, I’ll check the execution timings using timeit:

$ python -m timeit -n10000 -r50 'from random_mac import random_mac' 'random_mac()'
10000 loops, best of 50: 45.7 usec per loop
$ python -m timeit -n10000 -r50 'from random_mac import random_mac' 'random_mac(style=2000)'
10000 loops, best of 50: 49.1 usec per loop

The conclusion is that list comprehension (in this case) is a massive 6.9% faster!

Comments
  1. Troy Rose says:

    Hey, nice comparisons there Greg.

    I know this doesn’t have anything to do with map/lambda vs list comprehension vs generators, but if you ever DID care about performance when generating MAC addresses, this code does the same thing sans any fancy list stuff.


    import os;
    import struct;
    def random_mac():
    return "%02x:%02x:%02x:%02x:%02x:%02x" % struct.unpack_from('BBBBBB',os.urandom(6))

    Let the kernel do the work!

    $ python -m timeit -n 10000 -r50 ‘from random_mac import random_mac’ ‘random_mac()’
    10000 loops, best of 50: 76 usec per loop
    $ python -m timeit -n 10000 -r50 ‘from urandom_mac import random_mac’ ‘random_mac()’
    10000 loops, best of 50: 20 usec per loop

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s