Coding

How To Write Data Structures and Algorithms in Python

5 minute read | July 8, 2020

Written by:
Sakshi Gupta

Get expert insights straight to your inbox.

Data structures and algorithms can be implemented in a variety of programming languages. This article will help you learn data structures and algorithms using Python.

Springboard helps you understand how to implement data structures and algorithms in Python. Get started now!

Programming/Implementing Data Structures Using Python

Python is a versatile programming language with many user-defined data structures and algorithms. You will be able to rely on Python’s default data structures when you implement your own algorithms: they will be the static foundation upon which your dynamic code flows.

There are four main types of data structures that come by default in Python and don’t need to be imported from user libraries.

Default Python Data Structure 1: The List

The first is the list. This is similar to an array of objects that can store data in a sequence, except for one important difference: you can store multiple types of data with one another in a sequence. For example, you can store a sequence of strings combined with a sequence of integers.

A list is defined with bracket notation ([ list elements ]). You can use built-in indexing in Python to access a specific item within the list, with 0 being the first value of a list (accessed by slice notation, so for example, the_list[0]).

You can also use negative indexing to access different elements from the last to the first. You can add and delete items from the list.

In this example, we define a list with a mix of integers for the first three elements and strings for the last two. We then access the first item by slicing with index notation 0, and then the last item by slicing with index notation -1.

Default Python Data Structure 2: Tuples

Tuples are like lists, with one critical difference: tuples can’t modify elements within. You can add two different tuples together to make one larger tuple, but otherwise, you can’t modify the contents of the sequences contained within a tuple.

In other ways, tuples function much like lists: you can put together a sequence of mixed data types as we will with strings and integers.

In this example, you will see we’ve added two tuples together and formed a larger “mega_tuple.” But when we try to append to one of the tuples, we get an AttributeError, with no ability to add to a tuple through thelist.appendmethod.

Default Python Data Structure 3: Sets

Sets are like lists as well in terms of being a sequence of objects, but they too also have a key difference: in this case, sets only take unique values. So, if you have a list that has duplicate values within it and you try to convert it into a set, the resulting set will eliminate all duplicates and leave only the sequence of unique values in your original list.

In this example, we have defined a list with three duplicate elements. By converting it into a set with Python’s default in-builtset()method, we then get a set with the only unique value to print.

Default Python Data Structure 4: Dictionaries

Finally, dictionaries are a bit like the standard map implementation in Python, with a set of key-value pairs. You can access a certain value with a key. For example, if you had a dictionary of people by their ages, their names might be the key, and each key might return the value which would be their age in a number of years.

If we put in the key of Phil into the pre-defined dictionary, we now see his pre-defined age (26) returned in our console.

There are also user-defined data structures that hew closer to the standard data structures seen in other programming languages: arrays, queues, stacks, trees, graphs, hash maps, linked lists, and more. In practice, using custom classes and custom operators, you can define your own data structures and data types, making Python a versatile language that you can leverage to power different data structures and algorithms.

Get To Know Other Software Engineering Students

Abdelkareem ElSharief

Programming/Implementing Algorithms Using Python

Just like with data structures, the implementation of algorithms in Python is human-readable and versatile. We’ll go through a few examples of common algorithms and their implementation in Python.

Python Algorithm 1: Percent Change (Arithmetic Algorithm)

We’ll start with something simple: a function that calculates the % change between two values x1 and x2. Python is able to easily parse through arithmetic operations in the order desired. You can then construct a sequence of steps.

Python Algorithm 2: Insertion Sort (Sorting Algorithm)

A large part of the algorithmic effort is put into sorting values in large lists into some discernible order. In this case, we want to take an input (a list of numbers) and return them sorted from the least amount to the most amount.

How do we accomplish this? We take an input through a function and transform it to an output through a series of steps. In this case, we use a Python while loop to go through each value and shift it to a lower position if it is lower in value into a subselection of the list until every element in the array is dealt with. This is very similar to how you might sort a hand of cards: removing one card at a time and then inserting it into a sorted part of the hand until your hand is sorted from the lowest value to the highest.

Python Algorithm 3: Binary Search (Search Algorithm)

Now that we’re able to sort lists, we want to be able to search through them. Here’s the Python implementation of the binary search algorithm, which works best when it’s sorted.

This checks to see if the midpoint is your search term, then bisects the list to search for an item within the subset. If the item is on the list, it’ll return True—if not it’ll return False.

How Does Springboard Help You Learn Data Structures and Algorithms Using Python?

Springboard’s software engineering online bootcamps are comprehensive, accessible, and come with a job guarantee. (See here what a software engineer does.)

The Software Engineering Career Track is designed for those who have basic skills in JavaScript, an aptitude for problem-solving, and strong communication and collaboration skills.

The online, six-month, self-paced curriculum will help you master key aspects of front-end web development, back-end web development, databases, and data structures and algorithms. You will learn:

• The basics of Python
• How data structures are implemented in Python, from lists to dictionaries
• How to build websites in Python with Flask