I read about the similarities between the python list and c++ vector and it looks as if the only difference is python list is heterogeneous. Are there any other differences? How are they both implemented?
1 Answer
Both python list and c++ vector are implemented as dynamic arrays (https://en.wikipedia.org/wiki/Dynamic_array). (Essentially arrays that get reallocated when they are too small.) Now the important difference between the python and c++ version don't come from the data structures themselves, but rather from the language. In c++ you can store structs, primitive data types pointers etc. in a vector. But in python everything is a pointer in the sense that an e.g. an integer is stored in the heap and it has an annotation attached to it that says "i am an integer". That's required because python has a dynamic type system. And the elements stored in the list are only pointers to the actual elements. This mechanism also allows python to store different data types in the same list. This is another reason why python is kinda slow.
-
$\begingroup$ The standard guarantees a vector is laid out in memory consecutively. $\endgroup$– JuhoJul 6, 2020 at 19:46
heterogeneous
if a type system is not really present. $\endgroup$