How is Python's List Implemented?

后端 未结 9 749
野趣味
野趣味 2020-11-22 08:00

Is it a linked list, an array? I searched around and only found people guessing. My C knowledge isn\'t good enough to look at the source code.

相关标签:
9条回答
  • 2020-11-22 08:39

    As others have stated above, the lists (when appreciably large) are implemented by allocating a fixed amount of space, and, if that space should fill, allocating a larger amount of space and copying over the elements.

    To understand why the method is O(1) amortized, without loss of generality, assume we have inserted a = 2^n elements, and we now have to double our table to 2^(n+1) size. That means we're currently doing 2^(n+1) operations. Last copy, we did 2^n operations. Before that we did 2^(n-1)... all the way down to 8,4,2,1. Now, if we add these up, we get 1 + 2 + 4 + 8 + ... + 2^(n+1) = 2^(n+2) - 1 < 4*2^n = O(2^n) = O(a) total insertions (i.e. O(1) amortized time). Also, it should be noted that if the table allows deletions the table shrinking has to be done at a different factor (e.g 3x)

    0 讨论(0)
  • 2020-11-22 08:42

    This is implementation dependent, but IIRC:

    • CPython uses an array of pointers
    • Jython uses an ArrayList
    • IronPython apparently also uses an array. You can browse the source code to find out.

    Thus they all have O(1) random access.

    0 讨论(0)
  • 2020-11-22 08:44

    A list in Python is something like an array, where you can store multiple values. List is mutable that means you can change it. The more important thing you should know, when we create a list, Python automatically creates a reference_id for that list variable. If you change it by assigning others variable the main list will be change. Let's try with a example:

    list_one = [1,2,3,4]
    
    my_list = list_one
    
    #my_list: [1,2,3,4]
    
    my_list.append("new")
    
    #my_list: [1,2,3,4,'new']
    #list_one: [1,2,3,4,'new']
    

    We append my_list but our main list has changed. That mean's list didn't assign as a copy list assign as its reference.

    0 讨论(0)
提交回复
热议问题