In arrays the values of arrays stored in consecutive memory locations, ao I have to ask that is python list values saved in consecutive memory locations like arrays?
Asked
Active
Viewed 696 times
2
-
6How the list is stored in memory is an implementation detail that you can't rely on. – chepner Nov 15 '18 at 16:19
-
Check https://stackoverflow.com/questions/3917574/how-is-pythons-list-implemented – migron Nov 15 '18 at 16:22
-
1The list stores pointers to values elsewhere in memory. – hpaulj Nov 15 '18 at 16:37
-
@hpaulj thanks but these pointers are consecutive or not (I have to ask this actually)... – Usman Developer Nov 15 '18 at 16:42
-
Discussions that I've seen say that the pointer buffer is contiguous. When it runs out of growth room it copies those pointers to a new larger buffer. But that's an implementation detail. Your use of 'consecutive' might mean something different. – hpaulj Nov 15 '18 at 16:53
-
If you're looking for contiguous storage, have a look at [numpy.array](https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.array.html) – s3cur3 Nov 15 '18 at 18:04
-
Right. It doesn't matter, because you can't access the memory anyway. A list contains a set of object references. If you have a list of numbers, the NUMBERS are not stored consecutively. You might have a set of object pointers stored consecutively, and each object contains one integer. When you say "I have to ask", the real response is, "no, you don't". – Tim Roberts Jul 06 '23 at 01:30
2 Answers
0
In Cpython, Yes. It is consecutive.
That is also why when list operations that involve memmove or copy past almost whole list can be time-consuming and should be avoided.
For example, if you use
a = list(...)
a.pop(n) # n is not -1 or last index
It actually means this in C
if ((size_after_pop - index) > 0) {
memmove(&items[index], &items[index+1], (size_after_pop - index) * sizeof(PyObject *));
}
status = list_resize(self, size_after_pop);

runzhi xiao
- 186
- 6
-2
Python lists are actually arrays i have checked it
a = [i for i in range(10)]
for i in range(len(a)):
print(id(a[i]) , end=' ')
# [0, 1, 2]
# 140586625908944 140586625908976 140586625909008
you can see that all addresses are contiguous. the gap is 32 which is size of integer that is dedicated.

mohammad
- 1
-
3This is an implementation detail in CPython and can't be relied on. – CrazyChucky Jan 23 '23 at 13:27