Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is list pop(0) not an O(1) operation in python?

l = [1,2,3,4]

popping the last element would be an O(1) operation since:

  1. It returns the last element
  2. Changes a few fixed attributes like len of the list

Why can't we do the same with pop(0)?

  1. Return the first element
  2. Change the pointer of the first element (index 0) to that of the second element (index 1) and change a few fixed attributes?
like image 823
Nitin Siwach Avatar asked Oct 30 '25 08:10

Nitin Siwach


1 Answers

Lists could have been implemented to do what you suggest, but it would add complexity and overhead, for an operation better handled by collections.deque. All lists everywhere would need extra metadata to track how much empty space is at the front (important for handling the resize policy, and calling free on the right pointer when the list dies or gets resized), and the logic for when and how to resize would also become more complicated.

The tradeoff was not deemed worthwhile.

like image 146
user2357112 supports Monica Avatar answered Oct 31 '25 21:10

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!