Last active
August 2, 2018 20:28
-
-
Save barrachri/82c43ea9774eb086191a652e4fcaa871 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Small comparison between append VS insert and pop() VS pop(0)""" | |
SIZE_OF_THE_LIST = 1000 | |
ELEMENTS_TO_BE_REMOVED = 500 | |
def test_append(): | |
my_list = [] | |
for i in range(SIZE_OF_THE_LIST): | |
my_list.append(i) | |
return my_list | |
def test_insert(): | |
my_list = [] | |
for i in range(SIZE_OF_THE_LIST): | |
my_list.insert(0, i) | |
return my_list | |
def test_pop_end(): | |
a_list = list(range(SIZE_OF_THE_LIST)) | |
for i in range(ELEMENTS_TO_BE_REMOVED): | |
a_list.pop() | |
return a_list | |
def test_pop_beginning(): | |
a_list = list(range(SIZE_OF_THE_LIST)) | |
for i in range(ELEMENTS_TO_BE_REMOVED): | |
a_list.pop(0) | |
return a_list | |
if __name__ == '__main__': | |
import timeit | |
print(f"Adding {SIZE_OF_THE_LIST} elements to a list, one at a time") | |
time = timeit.timeit("test_append()", setup="from __main__ import test_append") | |
print(f" - `append(i)`, end of the list: {time}") | |
time = timeit.timeit("test_insert()", setup="from __main__ import test_insert") | |
print(f" - `insert(0, i)`, beginning of the list: {time}") | |
print(f"Removing {ELEMENTS_TO_BE_REMOVED} elements from a list of {SIZE_OF_THE_LIST} elements, one at a time") | |
time = timeit.timeit("test_pop_end()", setup="from __main__ import test_pop_end") | |
print(f" - `pop()`, end of the list: {time}") | |
time = timeit.timeit("test_pop_beginning()", setup="from __main__ import test_pop_beginning") | |
print(f" - `pop(0)`, beginning of the list: {time}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment