Skip to content

Instantly share code, notes, and snippets.

@corajr
Created August 25, 2017 16:13
Show Gist options
  • Save corajr/4739fac5ed678cecc267cabf4cbdd470 to your computer and use it in GitHub Desktop.
Save corajr/4739fac5ed678cecc267cabf4cbdd470 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import collections
Topic = collections.namedtuple("Topic", ["render_type"])
def mk_example(n, render_type="Topic"):
return [Topic(render_type=render_type) for _ in xrange(n)]
example = mk_example(25, "Topic") + mk_example(25, "Tutorial")
def test_for_loop():
topics_by_render_type = {"Topic": [], "Tutorial": []}
for t in example:
topics_by_render_type[t.render_type].append(t)
def test_list_comp():
topics = [t for t in example if t.render_type == "Topic"]
tutorials = [t for t in example if t.render_type == "Tutorial"]
if __name__ == '__main__':
import timeit
print(timeit.timeit("test_for_loop()", setup="from __main__ import test_for_loop"))
print(timeit.timeit("test_list_comp()", setup="from __main__ import test_list_comp"))
# python for_loop_list_comp.py
# for loop: 16.5271840096
# list comps: 23.9546978474
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment