Are Python lists dynamic
Implementation of Dynamic Array in PythonPythonServer Side ProgrammingProgramming Dynamic ArrayIn python, a list, set and dictionary are mutable objects. While number, string, and tuple are immutable objects. Mutable objects mean that we add/delete items from the list, set or dictionary however, that is not true in case of immutable objects like tuple or strings. Show In python, a list is a dynamic array. Let's try to create a dynamic list Add some items onto our empty list, list1 >>> # Add items >>> list1 =[2, 4, 6] >>> list1 [2, 4, 6] >>> # Another way to add items, using append. >>> list1.append('Tutorialspoint') >>> list1 [2, 4, 6, 'Tutorialspoint']Remove some item from a list From above we can see that list is actually an extension of an array, where we can modify(increase or decrease) the size a list. We started with a list of size zero and then add four items to it. Basics of the dynamic array implementationConsider an example where the list .i.e. list1 is appended when the size of the array is full then, we need to perform below steps to overcome its size limitation shortcoming. This is the basis behind the dynamic array implementation
Let's create a simple code on how to implement the dynamic array concept in python programming. We will create our own dynamic array class by using the built-in library class in python called ctypes which is going to be used as a raw array from the ctypes module. dynamicArray.pyimport ctypes class DynamicArray(object): #Initialize it def __init__(self): #We'll have three attributes self.n = 0 # by default self.capacity = 1 # by default self.A = self.make_array(self.capacity) # make_array will be defined later #Length method def __len__(self): #It will return number of elements in the array return self.n def __getitem__(self, k): #it will return the elements at the index k if not 0 <=kThats it, we have created our own dynamic array and we can resize the array which is a list in python. Karthikeya Boyini Published on 19-Feb-2019 11:47:14 Previous Page Print Page Next Page Advertisements |