Skip to content

Instantly share code, notes, and snippets.

@theladyjaye
Created October 27, 2012 16:55
Show Gist options
  • Select an option

  • Save theladyjaye/3965320 to your computer and use it in GitHub Desktop.

Select an option

Save theladyjaye/3965320 to your computer and use it in GitHub Desktop.
Python appending lists vs adding lists
from timeit import Timer
from itertools import islice
from itertools import cycle
def add_list_small(target, source):
target += source
def add_list_large(target, source):
target += source
def append_list_small_single(target, source):
target.append(source[0])
def append_list_large_single(target, source):
target.append(source[0])
def append_list_small_multi(target, source):
map(target.append, source)
# for item in source:
# target.append(item)
def append_list_large_multi(target, source):
map(target.append, source)
# for item in source:
# target.append(item)
if __name__ == "__main__":
list_small = list(islice(cycle('abcdef'), 20))
list_large = list(islice(cycle('abcdef'), 20000))
source_list_small = ['1']
source_list_large = list(islice(cycle('lmnopqrstuv'), 500))
print('-------- Small Lists ---------')
for func in add_list_small, append_list_small_single:
stmt = '{0.__name__}(list_small, source_list_small)'.format(func)
setup = "from __main__ import add_list_small, append_list_small_single, list_small, source_list_small"
print func.__name__, min(Timer(stmt, setup).repeat(50, 1000))
for func in add_list_large, append_list_large_single:
stmt = '{0.__name__}(list_large, source_list_small)'.format(func)
setup = "from __main__ import add_list_large, append_list_large_single, list_large, source_list_small"
print func.__name__, min(Timer(stmt, setup).repeat(50, 1000))
print('\n-------- Large Lists ---------')
for func in add_list_small, append_list_small_multi:
stmt = '{0.__name__}(list_small, source_list_large)'.format(func)
setup = "from __main__ import add_list_small, append_list_small_multi, list_small, source_list_large"
print func.__name__, min(Timer(stmt, setup).repeat(50, 1000))
for func in add_list_large, append_list_large_multi:
stmt = '{0.__name__}(list_large, source_list_large)'.format(func)
setup = "from __main__ import add_list_large, append_list_large_multi, list_large, source_list_large"
print func.__name__, min(Timer(stmt, setup).repeat(50, 1000))
@theladyjaye
Copy link
Copy Markdown
Author

-------- Small Lists ---------
add_list_small 0.000310897827148
append_list_small_single 0.000353097915649
add_list_large 0.000298023223877
append_list_large_single 0.000354051589966

-------- Large Lists ---------
add_list_small 0.0023410320282
append_list_small_multi 0.0300941467285
add_list_large 0.00239205360413
append_list_large_multi 0.0299570560455
[Finished in 4.6s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment