Hands-on with Linear data structures with Python

Data Structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. They can be broadly classified as primitive, composite/abstract/non-primitive data structures. Primitive structures are the basic units of storage like boolean, integer, float, double. These are not that significant when compared to other types. In this post we will discuss about linear data structures and how to implement them in python (with built-in data structures in python).

Non-primitive data structure

The Non-primitive data structure cannot be directly controlled by computer commands, we need to define and implement the operations supported by them. Depending on language you use, we have some DS come as built-in (like arrays in most of programming language). We can further group DS into:

  • Non-linear data structure

Non-linear data structure

Data items are not organized in a linear manner and can be associated with any other data element. For example, tree and graph.

Linear data structure

Data items are arranged in an orderly manner where the elements are attached adjacently.. For example, array, linked list, queue, stack.

Arrays & Linked-list

In python both array and list data structure are available by default i.e. they come in as built-in. Below section will describe how we can implement other data structures with the built-in ones.

source: https://laptrinhx.com/data-structures-you-need-to-learn-in-python-2469942955/

Stack

Definition:

Stack is a non-primitive and linear data structure. It works on the principle of LIFO (Last In First Out). That is, the element that is added recently is removed first, and the element that is added first is removed at the end. Operations supported:

  • Pop()

Implementation:

Lets use ‘list’ data structure to implement stack.

>> stack = ["a","b","c","d"]>> stack 
[‘a’, ‘b’, ‘c’, ‘d’]
>> stack.append("1")>> stack.append("2")>> stack.append("3")>> stack
>> [‘a’,’b’, ‘c’, ‘c’, ‘1’, ‘2’, ‘3’]
>> stack.pop()
‘3’
>> stack.pop()
‘2’
>> stack
[‘a’, ‘b’, ‘c’, ‘d’, ‘1’]

Queue

Definition:

Queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added first is removed first, and the element that is added last is removed last. Operations supported:

  • dequeue()

Implementation:

Let’s use ‘list’ data structure to implement stack.

>> from collections import deque
>> queue = deque([“a”, “b”, “c”, “d”])
>> queue
deque([‘a’, ‘b’, ‘c’, ‘d’])
>> queue.append(“1”)
>> queue.append(“2”)
>> queue
deque([‘a’, ‘b’, ‘c’, ‘d’, ‘1’, ‘2’])
>> queue.popleft()
‘a’
>> queue.popleft()
‘b’
>> queue
deque([‘c’, ‘d’, ‘1’, ‘2’])