Introduction to Data Structures and Algorithms with Python.
Tags: beginners, programming, tutorial, python
Published: 2022-02-19 21:27:04

##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))

```
<u>Other list functions</u>
`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.

_<u>Looping over lists</u>_

```
numbers = [1, 3, 6, 9]
for number in numbers:
    print(number)
```
`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)]
```


**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)
```
<u>Iterating over elements in a set</u>

```
numbers = {3, 7}
for x in numbers:
    print(x)
```
`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)
```


**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
<u>Functions we can perform on stacks</u>
`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.

<u>Uses of stacks</u>

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
 
<u>Queue operations</u>
`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 link](https://github.com/Torine6/pythonProject2/blob/master/main.py)to check out the codes used in the article.

**Other useful material**
[1. Difference between data structures and algorithms](https://medium.com/swlh/differences-between-data-structures-and-algorithms-eed2c1872cfc#:~:text=Data%20Structure%20is%20about%20organising,to%20reach%20the%20desired%20output.)
[2. Common data structures every programmer must know](https://towardsdatascience.com/8-common-data-structures-every-programmer-must-know-171acf6a1a42#:~:text=Data%20Structures%20are%20a%20specialized,Computer%20Science%20and%20Software%20Engineering.)
[3. Inbuilt data structures in Python](https://www.geeksforgeeks.org/inbuilt-data-structures-python/#:~:text=Python%20has%20four%20basic%20inbuilt,%2C%20Dictionary%2C%20Tuple%20and%20Set.&text=Lists%3A%20Lists%20in%20Python%20are,more%20like%20variations%20of%20lists.)
[4. Dictionaries in Python](https://www.tutorialsteacher.com/python/python-dictionary)
[5. User-defined data structures](https://www.geeksforgeeks.org/user-defined-data-structures-in-python/)
[6. Queues in Python](https://www.geeksforgeeks.org/queue-in-python/)
[7. Stacks in Python](https://www.geeksforgeeks.org/stack-in-python/#:~:text=Implementation%20using%20list%3A,the%20element%20in%20LIFO%20order.)
[8. Linked lists in Python](https://realpython.com/linked-lists-python/#introducing-collectionsdeque)
[9. How to create linked lists](https://www.educative.io/edpresso/how-to-create-a-linked-list-in-python)
[10. YouTube video](https://www.youtube.com/watch?v=pkYVOmU3MgA&t=632s)