简体   繁体   中英

Python list insertion run time complexity

I know that inserting to list is O(n) since the worst case is insert to index 0 .

Now my question is, what if we let A , B be lists such that len(A) = len(B) = N and we're trying to insert into A each element from B in that way:

A[0:0] = B

Is it going to take O(N^2) ?

From what I understand about how lists work in Python, using slicing to copy an list doesn't actually perform any insertions, it just replaces the element at every index in A with the element at the same index in B. It will take O(n) time because it's essentially performing a linear scan of list A, but with the additional step of assigning a new value to each index, which itself takes O(1) for each assignment.

On a side note, A[0:0] = B will not copy list B's contents into list A unless A is an empty list, ie, A = [] . Otherwise, the contents of B are prepended onto A, causing A to be of length 2N instead of N as is desired. This itself will take $O(n^2)$ because it essentially performs insertions of the worst case scenario for every element of list B.

If you want to overwrite any content inside list A by copying the contents of list B, I'd suggest the following:

A = B[:]

If this isn't what you're looking for, this GeeksforGeeks article lists quite a few different ways to copy a list into another.

It's expected to be linear ( O(n) ), but here is the experimental check (2 to 10^8 items, 100 runs each except the last 3 points (only 20)):

在此处输入图像描述

NB. there is non-negligible overhead for the first few points, likely due to constant operations (slicing, assignment).

Each point is calculated using timeit :

n = 10 # number or items in list, to make variable in a loop
r = 100 # or 20
t = {}
t[n] = timeit('A[0:0] = B', number=r,
              setup=f'A = list(range({n})) ; B = list(range({n}))'
              )/r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM