The Wayback Machine - https://web.archive.org/web/20240922014509/https://www.geeksforgeeks.org/implementation-of-dynamic-array-in-python/
Open In App

Implementation of Dynamic Array in Python

Last Updated : 12 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

What is a dynamic array?

A dynamic array is similar to an array, but with the difference that its size can be dynamically modified at runtime. Don’t need to specify how much large an array beforehand. The elements of an array occupy a contiguous block of memory, and once created, its size cannot be changed. A dynamic array can, once the array is filled, allocate a bigger chunk of memory, copy the contents from the original array to this new space, and continue to fill the available slots.

We’ll be using a built in library called ctypes of python . Check out the documentation for more info, but its basically going to be used here as a raw array from the ctypes module.

A quick note on public vs private methods, we can use an underscore _ before the method name to keep it non-public. 

For example:

Python




class M(object):
 
    def public(self):
        print 'Use Tab to see me !'
 
    def _private(self):
        print "You won't be able to Tab to see me !"


Python




m = M()
m.public()


Output:

Use Tab to see me!

Python




m._private()


Output:

You won't be able to see me!

Dynamic Array Logic Implementation:

The key is to provide means to grows an array A that stores the elements of a list. We can’t actually grow the array, its capacity is fixed. If an element is appended to a list at a time, when the underlying array is full, we need to perform following steps.

  1. Allocate a new array B with larger capacity (A commonly used rule for the new array is to have twice the capacity of the existing array )
  2. Set B[i]=A[i], for i=0 to n-1 where n denotes the current no of items.
  3. Set A=B that is, we hence forth use B as the array of supporting list.
  4. Insert new element in the new array.

Dynamic Array Code Implementation: 

Python3




import ctypes
 
 
class DynamicArray(object):
    '''
    DYNAMIC ARRAY CLASS (Similar to Python List)
    '''
 
    def __init__(self):
        self.n = 0  # Count actual elements (Default is 0)
        self.capacity = 1  # Default Capacity
        self.A = self.make_array(self.capacity)
 
    def __len__(self):
        """
        Return number of elements stored in array
        """
        return self.n
 
    def __getitem__(self, k):
        """
        Return element at index k
        """
        if not 0 <= k < self.n:
            # Check it k index is in bounds of array
            return IndexError('K is out of bounds !')
 
        return self.A[k]  # Retrieve from the array at index k
 
    def append(self, ele):
        """
        Add element to end of the array
        """
        if self.n == self.capacity:
            # Double capacity if not enough room
            self._resize(2 * self.capacity)
 
        self.A[self.n] = ele  # Set self.n index to element
        self.n += 1
 
    def insertAt(self, item, index):
        """
        This function inserts the item at any specified index.
        """
 
        if index < 0 or index > self.n:
            print("please enter appropriate index..")
            return
 
        if self.n == self.capacity:
            self._resize(2*self.capacity)
 
        for i in range(self.n-1, index-1, -1):
            self.A[i+1] = self.A[i]
 
        self.A[index] = item
        self.n += 1
 
    def delete(self):
        """
        This function deletes item from the end of array
        """
 
        if self.n == 0:
            print("Array is empty deletion not Possible")
            return
 
        self.A[self.n-1] = 0
        self.n -= 1
 
    def removeAt(self, index):
        """
        This function deletes item from a specified index..
        """
 
        if self.n == 0:
            print("Array is empty deletion not Possible")
            return
 
        if index < 0 or index >= self.n:
            return IndexError("Index out of bound....deletion not possible")
 
        if index == self.n-1:
            self.A[index] = 0
            self.n -= 1
            return
 
        for i in range(index, self.n-1):
            self.A[i] = self.A[i+1]
 
        self.A[self.n-1] = 0
        self.n -= 1
 
    def _resize(self, new_cap):
        """
        Resize internal array to capacity new_cap
        """
 
        B = self.make_array(new_cap)  # New bigger array
 
        for k in range(self.n):  # Reference all existing values
            B[k] = self.A[k]
 
        self.A = B  # Call A the new bigger array
        self.capacity = new_cap  # Reset the capacity
 
    def make_array(self, new_cap):
        """
        Returns a new array with new_cap capacity
        """
        return (new_cap * ctypes.py_object)()
 
# Instantiate
 
 
arr = DynamicArray()
 
# append the new elements
 
arr.append(1)
 
arr.append(2)
 
arr.append(3)
 
# length of the given append in array
 
print(len(arr))
 
# access the given append in array
 
print(arr[1])
 
print(arr[2])
 
# remove the given the array
 
arr.removeAt(2)
 
# length of the array
 
print(len(arr))
 
# index of the array
 
print(arr[1])
 
    #This code Contribute by Raja.Ramakrishna


Output:

3
2
3
2
2


Similar Reads

Register Array | Introduction, Implementation and Applications
A register array is a collection of contiguous registers in computer programming and digital hardware design. Registers are small and high-speed storage units within the computer's CPU that store data temporarily for processing. A register array allows for the efficient storage and retrieval of the data elements using index-based addressing. How to
8 min read
Python implementation of automatic Tic Tac Toe game using random number
Tic-tac-toe is a very popular game, so let's implement an automatic Tic-tac-toe game using Python. The game is automatically played by the program and hence, no user input is needed. Still, developing an automatic game will be lots of fun. Let's see how to do this. NumPy and random Python libraries are used to build this game. Instead of asking the
5 min read
Interesting Python Implementation for Next Greater Elements
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in array. Elements for which no greater element exist, consider next greater element as -1. Examples: Input : 11, 13, 21, 3, 9, 12 Output : 11 --&gt; 21 13 --&gt; 21 21 --&gt; -1 3 --
2 min read
Python 3.6 Dictionary Implementation using Hash Tables
Dictionary in Python is a collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is
3 min read
Shortest Path Problem Between Routing Terminals - Implementation in Python
The famous Dijkstra's algorithm can be used in a variety of contexts - including as a means to find the shortest route between two routers, also known as Link state routing. This article explains a simulation of Dijkstra's algorithm in which the nodes (routers) are terminals. Once the shortest path between two nodes (terminals) is calculated, the s
6 min read
Implementation of Hashing with Chaining in Python
Hashing is a data structure that is used to store a large amount of data, which can be accessed in O(1) time by operations such as search, insert and delete. Various Applications of Hashing are: Indexing in database Cryptography Symbol Tables in Compiler/Interpreter Dictionaries, caches, etc. Concept of Hashing, Hash Table and Hash Function Hashing
3 min read
Implementation of Composition (Has-A Relation) in Python
We can access the member of one class inside a class using these 2 concepts: By Composition(Has-A Relation)By Inheritance(Is-A Relation) Here we will study how to use implement Has-A Relation in Python. Implementation of Composition in Python By using the class names or by creating an object we can access the member of one class inside another clas
3 min read
Implementation of XOR Linked List in Python
Prerequisite: XOR Linked List An ordinary Doubly Linked List requires space for two address fields to store the addresses of previous and next nodes. A memory-efficient version of Doubly Linked List can be created using only one space for the address field with every node. This memory efficient Doubly Linked List is called XOR Linked List or Memory
6 min read
Python - Stop &amp; Wait Implementation using CRC
Stop and wait protocol is an error control protocol, in this protocol the sender sends data packets one at a time and waits for positive acknowledgment from the receiver's side, if acknowledgment is received then the sender sends the next data packet else it'll resend the previous packet until a positive acknowledgment is not received. Note: To get
7 min read
Internal implementation of Data Structures in Python
Python provides a variety of built-in data structures, each with its own characteristics and internal implementations optimized for specific use cases. In this article we are going to discuss about the most commonly used Data structures in Python and a brief overview of their internal implementations: Data Structure Internal Implementation Static o
3 min read
Random Walk (Implementation in Python)
Introduction A random walk is a mathematical object, known as a stochastic or random process, that describes a path that consists of a succession of random steps on some mathematical space such as the integers. An elementary example of a random walk is the random walk on the integer number line, which starts at 0 and at each step moves +1 or -1 wit
5 min read
Conway's Game Of Life (Python Implementation)
Conways's Game Of Life is a Cellular Automation Method created by John Conway. This game was created with Biology in mind but has been applied in various fields such as Graphics, terrain generation,etc.. The "game" is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with th
5 min read
Python | Implementation of Queues in Multi-Threading
Prerequisites: Before reading this article, some important background reading is recommended to ensure that one is well equipped with the basic knowledge of threads as well as the basic knowledge of queues before trying to mix the two together. The official documentation is especially important. Topic Source 1 Source 2 Source 3 Queues Wikipedia Art
7 min read
Monkey Patching in Python (Dynamic Behavior)
In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. # monk.py class A: def func(self): print (&quot;func() is being called&quot;) We use above module (monk) in below code and change behavior of func() at run-time by assigning differe
1 min read
Python | Implementing Dynamic programming using Dictionary
Dynamic Programming is one way which can be used as an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems so that we do not have to re-compute them when needed later. This simple opti
3 min read
Dynamic Attributes in Python
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for better understanding about the topic. Example 1:
2 min read
Detailed Analysis on affects of Dynamic Typing and Concurrency on Python?
Is python too slow? The reality is, Python is an extremely slow programming language when we look at something like Java, C, and C++ it's embarrassing how much faster they can do things than Python, in fact, specific algorithms and applications can actually do things about a hundred to two hundred times faster than the native Python language so in
7 min read
Python - Dynamic GUI Calculator using Tkinter module
Python provides many options for developing GUI like Kivy, PyQT, WxPython, and several others. Tkinter is the one that is shipped inbuilt with python which makes it the most commonly used out of all. Tkinter is easy, fast, and powerful. Beginners can easily learn to create a simple calculator using this article: Python | Simple GUI calculator using
3 min read
Scraping dynamic content using Python-Scrapy
Let's suppose we are reading some content from a source like websites, and we want to save that data on our device. We can copy the data in a notebook or notepad for reuse in future jobs. This way, we used scraping(if we didn't have a font or database, the form brute removes the data in documents, sites, and codes). But now there exist many tools f
4 min read
Introduction to Dynamic CLI in Python
In this article, we will see an introduction to Dynamic CLI in Python. What is Dynamic CLI? A Modern, user-friendly command-line HTTP client for API testing, It helps a programmer to code more efficiently by increasing one's productivity and by reducing the time and effort required to perform tasks of searching for solutions and making API requests
4 min read
Dynamic Testing of Values Against Python Literal Types
In Python, Literal types are a way to specify that a value must be one of a set of specific values. This can be useful for type checking and ensuring your code handles only expected values. However, dynamically testing whether a value conforms to a Literal type can be tricky. This article will guide you through understanding Literal types and imple
4 min read
Dynamic Forms Handling with HTMX and Python Flask
Dynamic forms enhance the user experience by updating the parts of a web page without the full page reload, the powerful library can allow for the AJAX requests and dynamic updates, while Flask can provide a robust backend framework for Python. This article will guide you through integrating the HTMX with Flask to create dynamic forms. HTMX: It can
4 min read
Implementation of K Nearest Neighbors
Prerequisite: K nearest neighbors Introduction Say we are given a data set of items, each having numerically valued features (like Height, Weight, Age, etc). If the count of features is n, we can represent the items as points in an n-dimensional grid. Given a new item, we can calculate the distance from the item to every other item in the set. We p
10 min read
UDP Client Server using connect | C implementation
UDP is a connection less protocol. There is no connection is established between client and server. Creating Standard UDP Client/Server is discussed here Prerequisite : Socket Programming in C/CPP | UDP server-client implementation In UDP, the client does not form a connection with the server like in TCP and instead, It just sends a datagram. Simil
3 min read
Implementation of Locking in DBMS
Locking protocols are used in database management systems as a means of concurrency control. Multiple transactions may request a lock on a data item simultaneously. Hence, we require a mechanism to manage the locking requests made by transactions. Such a mechanism is called a Lock Manager. It relies on the process of message passing where transacti
5 min read
Bellman Ford Algorithm (Simple Implementation)
We have introduced Bellman Ford and discussed on implementation here.Input: Graph and a source vertex src Output: Shortest distance to all vertices from src. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported.1) This step initializes distances from source to all vertices as infinite an
13 min read
QuickSelect (A Simple Iterative Implementation)
Quickselect is a selection algorithm to find the k-th smallest element in an unordered list. It is related to the quick sort sorting algorithm.Examples: Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15} k = 4 Output: 10 The QuickSelect algorithm is based QuickSort. The difference is, instead of recurring for
7 min read
Implementation of neural network from scratch using NumPy
DNN(Deep neural network) in a machine learning algorithm that is inspired by the way the human brain works. DNN is mainly used as a classification algorithm. In this article, we will look at the stepwise approach on how to implement the basic DNN algorithm in NumPy(Python library) from scratch. The purpose of this article is to create a sense of un
11 min read
Gibb's Phenomenon Rectangular and Hamming Window Implementation
What is Gibb's Phenomenon? Gibb's Phenomenon in Digital Filter's refer to the manner how a Fourier series of periodic functions behave near jump discontinuation, the partial sum of the Fourier series has large oscillations near the discontinuation, which might increase the maximum of the partial sum above that of the function itself. Thus, there is
5 min read
XOR Implementation in Tensorflow
In this article, we'll learn how to implement an XOR gate in Tensorflow. Before we move onto Tensorflow implementation we'll have a look at how the XOR Gate Truth Table to get a deep understanding about XOR. X Y X (XOR) Y 0 0 0 0 1 1 1 0 1 1 1 0 From the above truth table, we come to know that the output of the gate is 1 only when one of the inputs
5 min read
Article Tags :
Practice Tags :