Implementation of basic data structures in Python- 1 (Stacks)

A data structure is simply a way of organizing data so that it can be used effectively and easily. They are also essential ingredients in creating fast and powerful algorithms, A lot of Experts say the implementation of these structures aids in making code cleaner and easier to understand, I agree.

Data structures are concepts that you will find in almost all programming languages, and as a Python guy, I decided to share how they are implemented in Python starting from the very basics of them, Stacks.

Stacks

A good analogy of the stack data structure is a stack of books, the topmost book on the stack would be the one you put there last. Your browser`s history is also another example of a stack data structure in play, the last website you visited appears at the top of your history. Hopefully, you get the idea of what a stack is. Now let`s see some code.

In Python, a Stack can be implemented in two ways, using a List and using an Object-Oriented approach. Let's observe the list approach first. Consider a Palindrome, a Palindrome is a word that is spelled the same forwards and backward, such as Bob, Madam, racecar. We`re going to use stacks to process a string and find out if it's a Palindrome or not.

If the string “racecar” is used as an argument to the panlindrome_checker function, It returns True, if it's not then it returns False. Using the stack data structure, it is possible to examine the initial spelling of the argument as well as comparing it to its reverse version.

Object-oriented approach

At first glance, it`s clear that the object-oriented approach for implementing a Stack encompasses quite a lot more detail. The methods, “push”, “pop”, “size”, and “peek” are functions that collectively manage the stack in terms of insertions, deletions as well as readability. The mutator method “push” can be called to specifically attach an element to the end of the stack. The “pop” method, another mutator, deletes the last element while simultaneously revealing it via the return clause. Similarly, the accessor methods “size” and “peek” play vital roles in this rigid structure; “size” simply captures the number of elements present in the stack while “peek” reveals the last element of the stack.

Interestingly, Python lists ([]) are natively stacks, they have documented methods that can be used to pop off the last item of a collection (some_list.pop()), as well as append an item (some_list.append()). Even the peek method can be accessed using the -1 index (some_list[-1]). This means that they can operate in the last-in-first-out order.

A certified life Scientist, Software Engineer, Core Python Expert.