Data Structures and Algorithms with Python

The main difference between bad programmers and good programmers is whether they consider their code or their data structures and algorithms to be more important. Bad programmers worry about code. Good programmers care about data structures and algorithms. 

In this article, I’m going to introduce you to the complete knowledge you need about data structures and algorithms with Python to be better with programming and most importantly to crack your interview.

Also, Read – Machine Learning Full Course For free.

Why Data Structures and Algorithms are Important?

The data structures and algorithms provide a set of techniques for the programmer to effectively manage data. The programmer should understand the basic concepts of data management. For example, if the programmer wants to collect Facebook user details, the candidate needs to access and manage the data efficiently using data structure and algorithm techniques.

If the programmer does not know the structures of the data and the algorithms, he may not be able to write efficient code to handle the data. The concepts of data structure can be implemented in any programming language. They can write code in any programming language with minimal effort. If the programmer does not know the predefined algorithmic techniques, it may take longer to resolve the problem.

Data Structures and Algorithms: Data Structures

A data structure is nothing but a format used to store and organize data. Data structures are fundamental to programming and most programming languages ​​come with them built-in.

You already know how to use many of Python’s built-in data structures, such as lists, tuples, and dictionaries. In this section, you will learn how to create two additional data structures: stacks and queues.


A stack is a data structure like a list, you can add and remove items from a stack, except unlike a list, you can only add and remove the last item. If you have the list [1, 2, 3], you can delete any of the items it contains. If you have an identical stack, you can only remove the last item, 3. If you remove 3, your stack looks like [1, 2]. You can now delete the 2.

Once you delete the 2, you can delete the 1 and the stack is empty. Removing an item from a stack is called popping. If you put 1 back on the stack, it looks like [1]. If you put a two on the stack, it looks like [1, 2]. Putting an object on a stack is called pushing. This type of data structure, where the last element inserted is the first element removed, is called a last-in-first-out (LIFO) data structure.

You can imagine LIFO as a stack of dishes. If you stack five dishes on top of each other, you will need to remove all of the other dishes to access the bottom one of the stack. Think of each data item in a stack as a dish, to access it you need to extract the data on top.

Now, let’s see how to build stacks:

class Stack:
    def __init__(self):
        self.items = []

    def is_empty(self):
        return self.items == []

    def push(self, item):

    def pop(self):
        return self.items.pop()

    def peek(self):
        last = len(self.items)-1
        return self.items[last]

    def size(self):
        return len(self.items)
Code language: Python (python)

If you will create a new stack, it will be empty and the is_empty method will return True:

stack = Stack()
print(stack.is_empty())Code language: Python (python)

Output: True

When you add a new item to the stack, is_empty returns False:

stack = Stack()
print(stack.is_empty())Code language: Python (python)
Output: False

Call the pop method to remove an item from the stack, and is_empty will return True:

stack = Stack()
item = stack.pop()
print(stack.is_empty())Code language: Python (python)

Finally, you can take a look at the contents of the stack and get its size:

stack = Stack()

for i in range(0, 6):

print(stack.size())Code language: Python (python)


A queue is another data structure. A queue is also like a list; you can add and remove items from it. A queue is also like a stack because you can only add and remove items in a certain order. Unlike a stack, where the first item put in is the last item out, a queue is a first-in-first-out (FIFO) data structure: the first item added is the first item removed.

Imagine FIFO as a data structure representing a line of people waiting to buy movie tickets. The first person in line is the first person to get tickets, the second person in line is the second person to get tickets, and so on.

Let’s see how we can implement Queues with Python:

class Queue:
   def __init__(self):
       self.items = []

   def is_empty(self):
       return self.items == []

   def enqueue(self, item):
       self.items.insert(0, item)

   def dequeue(self):
       return self.items.pop()

   def size(self):
       return len(self.items)
Code language: Python (python)

If you create a new empty queue, the is_empty method returns True:

a_queue = Queue()
print(a_queue.is_empty())Code language: Python (python)
Output: True

To add items and check the queue size:

a_queue = Queue()

for i in range(5):

print(a_queue.size())Code language: Python (python)
Output: 5

To remove each item from the queue:

a_queue = Queue()

for i in range(5):

for i in range(5):

print(a_queue.size())Code language: Python (python)

With this, we completed the Data Structures and now let’s move to the Algorithms part of Data Structures and Algorithms with Python.

Data Structures and Algorithms: Algorithms

This section covers the complete knowledge of algorithms. An algorithm is a series of steps that can be taken to solve a problem. The problem may be searching for a list or printing the words to “99 Beer Bottles on the Wall”.

FizzBuzz Algorithm

It’s finally time to learn how to solve FizzBuzz, the popular interview question designed to eliminate candidates: write a program that prints the numbers from 1 to 100. But for the multiples of 3, print “Fizz” instead of number, and multiples of five print “Buzz.” For multiples of three and five, print “FizzBuzz”.

To solve this problem, you need a way to check if a number is a multiple of three, a multiple of five, both, or neither. If a number is a multiple of three, if you divide it by three, there is no remainder.

The same applies to five. The modulo (%) operator returns the remainder. You can solve this problem by going through the numbers and checking if each number is divisible by three and five, only three, only five, or none:

def fizz_buzz():
    for i in range(1, 101):
        if i % 3 == 0 and i % 5 == 0:
        elif i % 3 == 0:
        elif i % 5 == 0:

fizz_buzz()Code language: Python (python)

Sequential Search Algorithm

A search algorithm finds information in a data structure such as a list. A sequential search is a simple search algorithm that checks each item in a data structure to see if the item matches what it is looking for.

If you were playing cards and looking for a specific card in the deck, you probably searched sequentially to find it. You went through each map in the game one by one, and if the map wasn’t the one you were looking for, you moved on to the next map.

When you finally got to the map you wanted, you stopped. If you went through the entire deck without finding the map, you also stopped because you realized the map was not there. Here is an example of a sequential search in Python:

def ss(number_list, n):
    found = False
    for i in number_list:
        if i == n:
            found = True
    return found

numbers = range(0, 100)
s1 = ss(numbers, 2)
s2 = ss(numbers, 202)
print(s2)Code language: Python (python)

Palindrome Algorithm

A palindrome is a word spelt the same way forward and backwards. You can write an algorithm that checks if a word is a palindrome by reversing all the letters in the word and testing whether the reversed word and the original word are the same. If they are, the word is a palindrome:

def is_palindrome(word):
    word = word.lower()
    return word[::-1] == word

print(is_palindrome("Mom"))Code language: Python (python)

Anagram Algorithm

An Anagram is a word which is created by rearrange of the letters of another word. The word iceman is an anagram of cinema because you can rearrange the letters of either word to form the other. You can determine if two words are anagrams by sorting the letters in each word alphabetically and testing whether they are the same:

def is_anagram(w1, w2):
    w1 = w1.lower()
    w2 = w2.lower()
    return sorted(w1) == sorted(w2)

print(is_anagram("iceman", "cinema"))
print(is_anagram("leaf", "tree"))Code language: Python (python)

Count Character Occurrences

To count character occurrences, you’ll write an algorithm that returns the number of times each character appears in a string. The algorithm will iterate character by character through the string and keep track of the number of times each character appears in a dictionary:

def count_characters(string):
    count_dict = {}
    for c in string:
        if c in count_dict:
            count_dict[c] += 1
            count_dict[c] = 1

count_characters("Dynasty")Code language: Python (python)

So this is probably everything you need to know about data structures and algorithms to master your programming skills and to crack your interview. I hope you liked this article on Data Structures and Algorithms with Python. Feel free to ask your valuable questions in the comments section below.

Also, Read – Decorators in Python Tutorial.

Follow Us:

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1501

Leave a Reply