INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS WITH PYTHON
Tags: luxtechacademy
Published: 2022-02-21 21:09:19

 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlsfd0hd5ivqi4e1405h.jpg)
Hello! Welcome once more to another chapter in Python. We would be discussing about python lists, dictionaries, tuples, sets, queues, stack and linked list.


**Lists**

A list is a data structure in python which is **mutable** (its values can be changed once created), ordered elements in a sequence (they appear in a certain order, thereby enabling us access each element using indexing). Every element in a python list is known as a value. They are used to store multiple items in a single variable. The best part about lists, apart from indexing, is it can contain elements of different data types; strings, characters, integers, float, etc.
Another thing you need to know about lists is the elements in a list must not be unique, so it is possible to duplicate items.
Items in a list are contained in squared **braces**, like this; [Item1, Item2, Item3]

If you have studied other programming languages such as java or C, just to name a few, you’ll notice that this sounds similar to arrays. So, what’s the difference? 
Firstly, a List in python is a built-in data structure in Python and holds a collection of items, that is, to use Lists in python, we don’t need to import anything, we simply use this data structure in our code.
Using an Array in Python on the other hand, requires importing data structure** NumPy package **or **array module**. 
Example; using list vs using arrays in a  python program


**_- Using List_**

_list = [3, 6, 9, 12]
print(_list)
print(type(_list))

**_- Using Array_**

import array as arr
import numpy as np
_array = arr.array(“i”,[3,6,9,12])
print(_array)
print(type(array))
Or using Numpy arrays
_array_np = np.array([“numbers”, 3, 6, 9, 12])
print(_array_np)
print(type(_array_np))
			**Arrays vs List**

**_Arrays	_**                                       
Arrays need to be declared	        
Arrays can store data very compactly	
Arrays handle numerical operations very well
	 
**_Lists_**
Lists are not declared
Lists do do not store data in compactly, since they are built in python
Lists cannot directly handle mathematical operations.
 
**When should you use lists?**
Use lists when you want to store small data and you do not plan to use any mathematical operations.

**When should you use arrays? **
Use arrays if you have a very long sequence of items or large amount of data and plan on performing mathematical operations on it.

**Dictionaries**
Like Lists, dictionaries are built-in mutable data structures. Unlike lists, dictionaries are not indexed by a sequence of numbers, but by**_ keys_**. Dictionaries consists of keys and its associate _**values**_. Keys are immutable data types which can either be strings or numbers. 
Each key is unique within a dictionary and can, therefore, not be duplicated in the dictionary. It is based on a structure called the **_hash table_**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocifx8v7elwpd6u9nkjn.png)

A dictionary is represented by curly braces, {}, and contains the key and their values

**Creating a dictionary**
first_dict 	 = {
	“key1” : “value1”,
	“key2” : “values2”
}
**Example**: 
We will pair African countries with their capitals using python dictionaries
countries = [‘Cameroon’, ‘Nigeria’, ‘Kenya’]
capitals = [‘Yaoundé’, ‘Abuja’, ‘Nairobi’]

#Creating the dictionary
Africa = {‘Cameroon’:’ Yaoundé’, ‘Nigeria’:’Abuja’,’Kenya’:’Nairobi’}
print(Africa)

**Tuples**
Python tuples is simply a collection of immutable data objects separated by commas. They hold data in the order proved to them and like the lists, elements in a tuple can be accessed using indexing. Unlike the python list, tuples are easier to process and is more efficient in memory. 

**Creating tuples**
first_tuple = (‘nnene’, ‘geraldine’)
print(first_tuple)

first_tuple = ‘nnene’,’geraldine’
print(first_tuple)
Both codes produces the same thing which is (‘nnene’,’geraldine’)

**Sets**
A set in python is a mutable unordered collection of items or data types of which no element has a duplicate. Elements contained in a set are immutable. Sets can support mathematical operations like sets, intersection, symmetric difference just to name a few. It is based on a data structure called the hash table.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zi8qn6mvwozxqcz3ng1g.png)

If many values are present at the same index position, then the value is added to that index position, to form a Linked List. In, Python Sets are implemented using dictionary with dummy variables, where key are the members set with greater optimizations to the time complexity

**Creating Python Sets**

Sets are created by putting all items into curly braces, separated by comma or by using built-in set() function
#Sets with integers
int_set = {2, 4, 6}
print(int_set)
#Sets with mixed data types 
first_set = {2.0, “Welcome”, (4,6,8)}
print(first_set)

**Python Stacks and Queues**
Stacks and Queues are two often used data structures in programming. They are the earliest data structures defined computer science. Python lists can play the role of a stack or queue.
Stacks and queue are quite often implemented in an array or linked list. 
A Stack is a **_First-In-Last-Out (FILO)_** data structure for implementing the first come last serve approach. Adding an item to the top of the stack (**push**) makes it the first item you will remove (**pop**) from the top of the stack.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4h1j86gvn7xiqfnyudds.png)

**Stack operations**
Operations in stack includes; Adding, Deleting and 	Traversing
**_Adding _**: Adding an element in a stack is done at the top of the stack
**_Deleting_**: If there is no element in the stack , then an underflow occurs(underflow means popping more items in a stack than it actually contains), but if there exists elements in the stack, deletion occurs from the topmost element.
**_Traversing_**:  This is visiting every element in a stack


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u2dxazv11nt6mutt17z2.png)

**Characteristics of stacks**

- It is used to parsing the operations. Parsing means processing a piece of code and turning it into machine language
- Duplicating items are allowed
- The order in which you insert in a stack is preserved

A Queue is a **First-In-First-Out (FIFO)** data structure for implementing a first come first serve approach in programming for sorting. Adding an item (**enqueue**) at the terminal end of a queue will be accessed last (**dequeue**).


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v5e2jrt3rn1ghl46n8rj.png) 


**Operations in queues**
**Adding**: Addition of elements in a queue takes place at the rear end, that is, the back of the queue.
**Deleting**: If there are no elements in the queue, deleting elements results to underflow, else the elements at the front is deleted.
**Traversing**: This is visiting every element in the queue. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5qqx7wsj7kcquauulad6.png)

**Characteristics of queues**
- It is very useful for parsing CPU task operations
- Elements in the queue can be repeated
- Insertion order is preserved.

**Python Linked lists**

A linked list is a data structure made of a chain of node objects and each node has a value and a pointer to the next node in chain and are preferred over arrays due to their dynamic size.

**Creating Linked list**

This is done using the node class. A Node object and another node class is created to use the other object.
Next, appropriate values are passed via the node object pointing to the next data elements.