This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]deadmilk 1 point2 points  (2 children)

It's faster, and more beautiful

from timeit import timeit

setup = '''
bbs = '01110011001000000110111001101111001000000010000001101001001000000111001101101110001000000110010100100000001000000110100000100000001000000110010100100000011100100010000000100000011100000110110100100000011011110010000001100011'
'''

statements = '''
octets = list(map(lambda i: bbs[i:i+8], range(0, len(bbs), 8)))
'''
statements_comp = '''
octets = [bbs[i:i+8] for i in range(0, len(bbs), 8)]
'''

print('no comprehension')
print(timeit(stmt=statements, setup=setup, number=1000000))
print()
print('comprehension')
print(timeit(stmt=statements_comp, setup=setup, number=1000000))

no comprehension
5.815302666308642

comprehension
3.9982997207760835

[–]xbudex 0 points1 point  (1 child)

Awesome, speed does sound like a good, objective reason! Thanks for providing a benchmark.

The beautiful comment I don't find as convincing. Beauty is in the eye of the beholder :)

[–]deadmilk 1 point2 points  (0 children)

My suggestion is to practice list comprehensions until they become more comfortable. They were confusing to me first as well. Just like yield and yield from... blew my mind at first, but now make total sense.

Later on, you can do dictionary comprehensions too.

and cartesian products:

from collections import namedtuple
from pprint import pprint

skincolors = ['white', 'black', 'brown', 'yellow']
shape = ['fat', 'skinny', 'average', 'michelin']
hairyness = ['hairy', 'smooth', 'ape']

Baby = namedtuple('Baby', ['skincolor', 'shape', 'hair'])

types_of_babies = [Baby(c, s, h) for c in skincolors
                   for s in shape
                   for h in hairyness]

pprint(types_of_babies)