DEV Community

Cover image for Introduction to Data Structures and Algorithms With Python
NancyKibunga
NancyKibunga

Posted on

Introduction to Data Structures and Algorithms With Python

Welcome back!
By now, you are already familiar with python basics. If you missed the article on Introduction to Modern python, you can catch up by clicking on the link below.

https://dev.to/nancykibunga/introduction-to-modern-python-4bil

The key concepts we are going to use today may be common in other programming languages. However, there exists key identities which differentiate them for use in various languages. Today we cover data structures and algorithms. Specifically, we will cover lists, dictionaries, tuples, sets, queues, stacks and linked lists.

Lists
We start with lists. These are created by placing elements inside square brackets, [], separated by commas. This way, they can store multiple items in a single variable. some characteristics of items in a list include: they are ordered. Lists are indexed from 0. Values in a list can be changed and lists allow duplicate values. They can be of any data type.
Example:

my_list = [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
my_list = [1, "Hello", 3.4]
Enter fullscreen mode Exit fullscreen mode

Dictionaries
Ploughing on to dictionaries. This is an is an unordered collection of data values, used to store data values in key values pairs within curly braces { }. Each key value is separated using a comma. Dictionaries use semicolon to separate the key and the value. Dictionaries do not allow duplicates.
Example:

Image description
Tuples
Moving on to tuples. A tuple is a fixed size grouping of elements, such as an (x, y) co-ordinate. The items in a tuple are ordered using parenthesis or common brackets. Data in a tuple cannot be manipulated. Hence, tuples are immutable. Tuples are written with round brackets.
Example

thistuple = ("anna", "joash", "suzie", "anna", "linet")
print(thistuple)
Enter fullscreen mode Exit fullscreen mode

Sets
For sets, they are defined as a collection which is unordered, unchangeable, and unindexed. A set does not hold duplicate items. Set items are unchangeable. However, you can remove or add (manipulate) items in a set. Sets are written with curly brackets
Example

#integers
my_set = {1, 2, 3}
print(my_set)

#mixed datatypes
my_set = {5.0, "jane", (7, 3, 6)}
print(my_set)
Enter fullscreen mode Exit fullscreen mode

Queues
Now onto queues. This is a linear data structure that stores items in First In First Out (FIFO) manner. The least recently added item is removed first. Queue in Python can be implemented by the following ways:

• List - List is a Python’s built-in data structure that can be used as a queue

• collections.deque - Queue in Python can be implemented using deque class from the collection’s module. Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of container

• queue.Queue- Queue is built-in module of Python which is uses FIFO rule to implement a queue. queue.Queue(maxsize) initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means a infinite queue.
Example

# Python program to
# demonstrate queue implementation
# using list

# Initializing a queue
queue = []

# Adding elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')

print("Initial queue")
print(queue)

# Removing elements from the queue
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))

print("\nQueue after removing elements")
print(queue)

# Uncommenting print(queue.pop(0))
# will raise and IndexError
# as the queue is now empty


Enter fullscreen mode Exit fullscreen mode

Stack
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only.
Stack in Python can be implemented using the following ways:
• list - Instead of push(), append() is used to add elements to the top of the stack while pop() removes the element in LIFO order.

• Collections.deque - Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container

• queue.LifoQueue - Data is inserted into LIFO Queue, which is basically a Stack. using the put() function and get() takes data out from the Queue.
Example

# Python program to
# demonstrate stack implementation
# using list

stack = []

# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')

print('Initial stack')
print(stack)

# pop() function to pop
# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())

print('\nStack after elements are popped:')
print(stack)

# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty

Enter fullscreen mode Exit fullscreen mode

Linked List
A linked list is a sequence of data elements, which are connected together by links. It has a dynamic size making it easy to insert or delete items. It is created using a node object and create another class to use this node object. then pass the appropriate values through the node object to point the to the next data elements, linking one node with the other.
Example

class Node:
   def __init__(self, dataval=None):
      self.dataval = dataval
      self.nextval = None

class SLinkedList:
   def __init__(self):
      self.headval = None

list1 = SLinkedList()
list1.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
# Link first Node to second node
list1.headval.nextval = e2

# Link second Node to third node
e2.nextval = e3
Enter fullscreen mode Exit fullscreen mode

Resources
https://www.tutorialspoint.com/python_data_structure/
https://www.programiz.com/python-programming
https://www.w3schools.com/python/
https://www.geeksforgeeks.org/python-programming-language
http://net-informations.com/python
https://docs.python.org/3/

Top comments (0)