I’m from C and python is new to me. I know that both insert and append can do the same task of appending an element to a list.
// this is just an EXAMPLE
Using append:
x: list[int] = []
total_elements: int = 0
# inserting
for i in range(5):
x.append(i)
total_elements += 1
# printing
for element in x:
print(f"{element} ", end = "")
print(f"n{total_elements} elements in list")
and using insert:
x: list[int] = []
total_elements: int = 0
# inserting
for i in range(5):
x.insert(total_elements, i)
total_elements += 1
# printing
for element in x:
print(f"{element} ", end = "")
print(f"n{total_elements} elements in list")
both will output:
0 1 2 3 4
5 elements in list
Say, my list keeps growing and growing. And say I want to track the number of elements too. insert() can access the index after the last index (for example, with list size of 100, I can do x.insert(total_elements, num)
.
Which one would be better and efficient in time consumption, insert or append?
EDIT: Sorry if my question was kind of misleading. The linked question is about PREPENDING, not appending. Before posting my question, I had read that question along with the suggested answers, insert(0,item)
is bad because it shifts all the pointers in the array. What I want to ask is APPENDING, since I use insert(total_elements, item)
to append. I want to track the number of elements too.
Also thank you for pointing out the more readable and efficient printing code using for element in x:
9
From python FAQ:
CPython’s lists are really variable-length arrays, not Lisp-style
linked lists. The implementation uses a contiguous array of references
to other objects, and keeps a pointer to this array and the array’s
length in a list head structure.This makes indexing a list a[i] an operation whose cost is independent
of the size of the list or the value of the index.When items are appended or inserted, the array of references is
resized. Some cleverness is applied to improve the performance of
appending items repeatedly; when the array must be grown, some extra
space is allocated so the next few times don’t require an actual
resize.
I recommend to read Laurent Luce’s article to understand how Python list is implemented and how append()
vs insert()
work.
Regarding you question:
As you can see below append
is faster BUT there are faster ways. The best one In this test is list comprehension.
I didn’t used map
because map
in python3 returns 'map' object
which needs to converted to list using list()
(and takes the fun out of the test).
Results:
Using list() 0.7724313329672441
Using listc 1.007791625102982
Using Append 1.175513125024736
Using Insert 1.6196119580417871
Using Extend 2.6952341250143945
Using += 2.795624832971953
The code:
import timeit
import inspect
def using_list():
l = list(range(5000000))
def using_listc():
l = [i for i in range(5000000)]
def using_append():
l = []
for i in range(5000000):
l.append(i)
def using_insert():
l = []
for i in range(5000000):
l.insert(i,i)
def using_extend():
l = []
for i in range(5000000):
l.extend([i])
def using_add():
l = []
for i in range(5000000):
l += [i]
if __name__ == '__main__':
using_list_code = inspect.getsource(using_list) + 'using_list()'
using_listc_code = inspect.getsource(using_listc) + 'using_listc()'
using_append_code = inspect.getsource(using_append) + 'using_append()'
using_insert_code = inspect.getsource(using_insert) + 'using_insert()'
using_extend_code = inspect.getsource(using_extend) + 'using_extend()'
using_add_code = inspect.getsource(using_add) + 'using_add()'
number_of_runs = 10
t = timeit.timeit(stmt=using_list_code, number=number_of_runs)
print(f'Using list() {t}')
t = timeit.timeit(stmt=using_listc_code, number=number_of_runs)
print(f'Using listc {t}')
t = timeit.timeit(stmt=using_append_code, number=number_of_runs)
print(f'Using Append {t}')
t = timeit.timeit(stmt=using_insert_code, number=number_of_runs)
print(f'Using Insert {t}')
t = timeit.timeit(stmt=using_extend_code, number=number_of_runs)
print(f'Using Extend {t}')
t = timeit.timeit(stmt=using_add_code, number=number_of_runs)
print(f'Using += {t}')
1
Append is more efficient with O(1) as it always adds to the end of the list. Insert will be less efficient with O(n) as it will move around items as it needs to deal with cases of inserting in the middle.
Hope this helped
2