简体   繁体   中英

What's the time complexity for some python list operations?

I know it is some kind of basic question but I am not good at the fundamental things. I only know that for stack pop() method pops out the last element with O(1) time.

In python, it's allowed to pop any position in a list as well as to insert an element to any position, ie list.pop(index) and list.insert(index, item) . If the length of a list is n , what's the average time complexity of them?

Besides, is there a difference between list.insert(index, item) and list = list[:index] + [item] + list[index:] ?

Thank you very much for the help!

While list.insert(index, item) does practically the same thing as list = list[:index] + [item] + list[index:] , the python built-in function list.insert was made as a faster way to insert an item into a list. list.insert is more advanced and is not equivalent to list = list[:index] + [item] + list[index:] becuase it uses a different algorithim and is much faster.

The time complexity is O(n), which is approximately n/2.

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