DEV Community

Cover image for Introduction to Data Structures and Algorithms with Python.
Torine6
Torine6

Posted on

Introduction to Data Structures and Algorithms with Python.

FAQs

i) What are data structures?
ii) What are algorithms?

Algorithms are like verbs and data structures are like nouns. An algorithm is just a method of doing something on a computer, a data structure is layout for memory that represents some sort of data. -Om Singh

In this article, we are going to look at the basic data structures and algorithms in Python that every beginner should know. First, let us define data structures and algorithms in layman's language to help us have a general outlook of what they are.

Data structures are simply the different ways of organizing and storing data in our computers so as to perform operations on the data.

Algorithms are the operations that we can perform on different data structures and the set of instructions for executing them.

Data structures and algorithms help us write efficient software.

DATA STRUCTURES

Built-in data structures
There are four types of built-in data structures in Python: lists, tuples, sets and dictionaries.

1.Lists
A list is an ordered collection of items.
It is a type of data used to represent/ store a list of objects in a single variable.
Lists are given descriptive names.
We use square brackets ([ ]) to create a list.
Items inside a list are separated using commas.
We use print()function to print the output on the terminal.
Lists are indexed from 0.
We can create lists that contain objects of any data type including strings, numbers, Booleans.

# creating a list
numbers = [2, 5, 7, -10]
print(numbers)

# adding a new element at the end of a list
numbers.append(3)
print(numbers)

# adding an item at a specific place in the list
numbers.insert(0, 45)

# removing last element from list
numbers.pop()
print(numbers)

# to access an element on the list
print(numbers[0])

# to modify an element
numbers[0] = 8
print(numbers)

# to determine number of items on a list
print(len(numbers))

# to check index of an item
print(numbers.index(7))

Enter fullscreen mode Exit fullscreen mode

Other list functions
in-to check whether an item exists on our list or not.
for-to iterate over all values.
extend-to append lists.
count-to know how many times a value appears on the list.
sort-to arrange items on a list in alphabetical order.
reverse-to reverse the order of lists.
del-to remove a range of elements from a list.
remove-to remove an element from a list.
clear-to remove all elements from a list.

Looping over lists

numbers = [1, 3, 6, 9]
for number in numbers:
    print(number)
Enter fullscreen mode Exit fullscreen mode

output
1
3
6
9

2.Tuples
A tuple is an ordered collection of items.
A tuple is used to store a sequence of objects.
A tuple is immutable, it cannot be modified or changed after it is created.
We create tuples using open and close () parentheses.
Tuples are indexed from 0.

# creating tuples
coordinates = (12, 5)
print(coordinates)

# accessing tuples using their index
print(coordinates [1])

# creating a list of tuples
coordinates = [(12, 5), (8, 20)]
Enter fullscreen mode Exit fullscreen mode

3.Sets
A set is an unordered collection of items which have no duplicates.
To remove duplicates from lists, we convert them into sets.
A set is mutable, it can be changed or modified once created.
Each element in a set must be unique.
We define sets using curly braces { } or by using the built-in set function.

# removing duplicates from a list
numbers = [9, 16, 3, 4, 9, 3]
unique_numbers = set(numbers)
print(unique_numbers)

# union of sets
first_set = {3, 4}
second_set = {5, 6}
print(first | second)

# intersection of sets
print(first_set & second_set)

#difference between two sets
print(first_set - second_set)

#symmetric difference
print(first_set ^ second_set)
Enter fullscreen mode Exit fullscreen mode

Iterating over elements in a set

numbers = {3, 7}
for x in numbers:
    print(x)
Enter fullscreen mode Exit fullscreen mode

output
3
7

4.Dictionaries
A dictionary is an unordered collection of items.
Dictionaries allow us to store information in key-value pairs, each key is associated with a different value.
The key must be unique and immutable.
Keys are case sensitive.
We can use strings, numbers or tuples as keys.
We separate the key from its value using a colon ( : ).
The value can be any data type.
We can assign one value to multiple keys.
Items in a dictionary are separated using commas( , ).
We can create dictionaries using dict() method.

# creating a dictionary 
user = {"name": "Paula", "age":28, "hobbies": ["dancing", "singing"]}
print(user)

# accessing a specific key
print(user["name"])

# specifying a default value for keys that do not exist
print(user.get("email", "Invalid key"))

# adding a key to the dictionary
user["email"] = "lady@gmail.com"
print(user.get("email"))

# changing value of a key 
user[name] = "Pam"
print(user)

# to modify several or all values
user.update({"name": "Reuben", "age": 21, "email": "kreuben@gmail.com"})

# to delete a key
del user["hobbies"]
print(user)

# looping through keys and values
for key, value in user.items():
    print(key, value)
Enter fullscreen mode Exit fullscreen mode

User-defined data structures
These are data structures that are not supported by Python, but can be programmed by the user to function similarly to Python built-in data structures.
We will look at stacks, queues and linked lists.

1.Stacks
A stack is a linear data structure that follows the LIFO(Last In First Out) principle.
A good example of a stack is a browser.
Stacks in Python can be implemented using lists, Collections.deque, queue.LifoQueue
Functions we can perform on stacks
append/ push() -to add an item on top of the stack.
pop() -to remove an item on top of the stack.
peek/ top() - to view the top element of the stack.
size()-returns the size of the stack.
[-1] -to get the item that is on top of the stack. It only works if our stack is not empty.
empty()-to return whether the stack is empty.

Uses of stacks

  1. Used for calling a function.

  2. Undo uses stacks to track down the last set of operations.

2.Queues
A queue is a linear data structure that follows FIFO(First In First Out) principle.
Insertion and deletion in queues happens on the rear-end and front-end.
Example of a queue is where customers line up for a resource.
In Python, queues can be implemented using lists, collection.deque, queue.Queue

Queue operations
enqueue - to add an item to the queue.
dequeue - to remove an item from the queue.
front - to get the first item from the queue.
rear - to get the last item from the queue.

3.Linked list
A linked list is a data structure for storing a collection of items.
A linked list can be visualized as several boxes connected to each other.
The data used in linked lists can be strings, numbers, characters, etc.
Linked lists can be used to implement stacks, queues and graphs.

NOTE

Use this linkto check out the codes used in the article.

Other useful material
1. Difference between data structures and algorithms
2. Common data structures every programmer must know
3. Inbuilt data structures in Python
4. Dictionaries in Python
5. User-defined data structures
6. Queues in Python
7. Stacks in Python
8. Linked lists in Python
9. How to create linked lists
10. YouTube video

Top comments (0)