Reputation: 923
According to resources I have read, list data structure in python is implemented with arrays. However, python list can contain different types of objects. If it's underlying data structure is array, how can the array contain different types of objects ?
Am I wrong that the array is of specific data type ?
Upvotes: 1
Views: 1371
Reputation: 1673
I give you program example here You can easily understand How objects store in list
class my_class:
def __init__(self):
self.var=1
def setparameter(self,txt):
self.txt=txt
objects = [my_class() for i in range(3)] # creates multiple objects here
for obj in objects:
obj.setparameter(5)
Objects in a list are pointer for class instances. See its data structures
See another example these lists are pointer for sublists
List of list
a=[[1,2,34],[12,4,5]]
Upvotes: 2
Reputation: 164643
Python lists store references to data, not the data itself. Direct from python source code object.h
:
Objects are always accessed through pointers of the type 'PyObject *'. The type 'PyObject' is a structure that only contains the reference count and the type pointer. The actual memory allocated for an object contains other data that can only be accessed after casting the pointer to a pointer to a longer structure type.
The comments in the source code are detailed and descriptive, if you require more detailed information.
Upvotes: 2
Reputation: 16942
You are wrong that it is an array of a specific type. A Python list is implemented as an array of references to (directly or indirectly, memory addresses of) other Python objects. There is more to it than that because there is a lot of housekeeping stuff as well.
Upvotes: 1