insert() or append() when APPENDING a list?

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật