0
$\begingroup$

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?

$\endgroup$
2
  • $\begingroup$ It's not really heterogeneous if a type system is not really present. $\endgroup$
    – user28434
    Jul 6, 2020 at 13:54
  • $\begingroup$ So is there any difference? $\endgroup$ Jul 6, 2020 at 14:13

1 Answer 1

3
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ The standard guarantees a vector is laid out in memory consecutively. $\endgroup$
    – Juho
    Jul 6, 2020 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.