Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python store lists internally?

How are lists in python stored internally? Is it an array? A linked list? Something else?

Or does the interpreter guess at the right structure for each instance based on length, etc.

If the question is implementation dependent, what about the classic CPython?

like image 389
Mike Cooper Avatar asked Jul 07 '09 02:07

Mike Cooper


People also ask

How do Python lists work internally?

Python lists are internally represented as arrays. The idea used is similar to implementation of vectors in C++ or ArrayList in Java. The costly operations are inserting and deleting items near the beginning (as everything has to be moved). Insert at the end also becomes costly if preallocated space becomes full.

How is a list stored in Python?

Lists can contain any Python object, including lists (i.e., list of lists). Lists are indexed and sliced with square brackets (e.g., list[0] and list[2:9]), in the same way as strings and arrays. Lists are mutable (i.e., their values can be changed in place).

How are lists stored in memory?

Lists, then, are stored in distinct chunks of memory which are linked together with pointers, which enables efficient use of memory generally and doesn't require resizing. It also allows for the easy and quick manipulation of pointers when transforming the list.

Are Python lists stored sequentially?

Although Python lists are not fixed-size and constrained like arrays in C++ or Java, they are still array type data structures where the items contained are stored in memory sequentially and accessed by an index number representing the memory block for a specific element. A list object can contain duplicate elements.


1 Answers

from Core Python Containers: Under the Hood
List Implementation:
Fixed-length array of pointers
* When the array grows or shrinks, calls realloc() and, if necessary, copies all of the items to the new space
source code: Include/listobject.h and Objects/listobject.c
btw: here is the video

like image 53
sunqiang Avatar answered Sep 22 '22 16:09

sunqiang