DEV Community

Cover image for DATA STRUCTURES AND ALGORIYHMS WITH PYTHON
SHEM MAINA
SHEM MAINA

Posted on • Edited on

DATA STRUCTURES AND ALGORIYHMS WITH PYTHON

Python is a language that has been put to use in many industrial fields ranging from machine learning, artificial intelligence to data science and many more. To fully maximize the usage of python, there is data that is used to make cases and enhance usability. This data has to be stored well and can be easily retrieved. This process of storing and being able to manipulate it is what we call data structures. Algorithms are tools that help us to manipulate the data in various ways.

There are two types of data structures in python; Built-in data structures and user-defined data structures

## BUILT-IN DATA STRUCTURES
These are data structures that come pre-loaded in python (also known a implicit). They include: dictionaries, lists, sets and tuples.

1.Lists

  • they are used to hold data of various types in a logical order. Every element of the list has an address, which is referred to as the Index. The index value starts at 0 and continues until the last element, which is referred to as the positive index. Negative indexing, which begins at -1, allows you to access elements from the last to the first. To create lists you use square brackets []. Let's use an example application to help us better comprehend lists.
my_list=[] #create an empty list
my_list=[1,3,4, 'example ',3.142]
print(my_list) #prints (1,3,4, 'example' , 3.142)
Enter fullscreen mode Exit fullscreen mode

There are a lot of ways to manipulate list like adding elements, deleting elements and accessing elements.
adding elements

  • The append() function combines all of the elements passed to it into a single element.
  • The extend() function adds the elements to the list one by one.
  • The insert() function adds the element passed to the index value while also increasing the list's size.
my_list=[1,2,3]
print(my_list)#outputs
my_list.append([66, 67, 'another example'])
print(my_list)#outputs [1,2,3 [66,67, 'another example']]
my_list.insert(2, 'insert example')
print(my_list)#outputs [1,2, 'insert example',3 [66,67, 'another example']]
Enter fullscreen mode Exit fullscreen mode

deleting elements
To delete elements, use the del keyword, which is built into Python, but it does not return anything.

my_list=[1,2,3, 'example',69,'example2', 3.142]
print(my_list)
del my_list[5]#removes element index 5 from list
print(my_list)#outputs[1,2,3, 'example',69, 3.142]
my_list.remove('example')#removes element with the value 'example' from the list
print(my_list)#outputs [1,2,3,69, 3.142]
my_list.pop(3)#pops element with index 3 from the list
print(my_list)#output  [1,2,3, 3.142]
my_list.clear()#clears the list
print(my_list)#outputs an empty list
Enter fullscreen mode Exit fullscreen mode

accessing elements in lists
You pass the index values hence you access the element in your desired index.

#accessing elements
my_list=[1,2,3, 'example',69,'example2', 3.142, 678, 'last element']
for element in my_list: #access elements one by one
    print(element)
print(my_list)#access the whole list
print(my_list[2:5])#access element from index 2 to 5
print(my_list[-1])#access list in reverse
Enter fullscreen mode Exit fullscreen mode

Besides these bsic functions, there are others like len() which shows the length of the list and sort() which sorts your list.

Tuples

A tuple is similar to a list except that it's a collection which is ordered and unchangeable. To create tuples, we use parenthesis().
example

#create a tuple
my_tuple=(1,44,3.142, 'tuple example')
print(my_tuple)
Enter fullscreen mode Exit fullscreen mode

Most functions used to manipulate tuples are similar to those of lists which I have demonstrated above with exceptions such as;
to append tuples, we use + sign

my_tuple=(1,44,3.142, 'tuple example')
print(my_tuple)
my_tuple=my_tuple+(4,4,6,'another tuple')#append a tuple
print(my_tuple)#output (1, 44, 3.142, 'tuple example', 4, 4, 6, 'another tuple')
Enter fullscreen mode Exit fullscreen mode

Dictionaries

Data values are stored in key:value pairs using dictionaries.
A dictionary is a collection that is ordered*, changeable, and does not tolerate duplicates.
Dictionaries can be created using the flower braces or using the dict() function. You need to add the key-value pairs whenever you work with dictionaries.

writing dictionaries

_dict={}
dict['one']='This is one'
dict[2]='This is two'
tinydict={'name':'John','code':'6000', 3:'zendaya'}
print (dict['one'])
print (dict[2])
print (tinydict)#outputs {'name': 'John', 'code': '6000', 3: 'zendaya'}

tinydict
print(tinydict.keys())# outputs dict_keys(['name', 'code', 3])
print(tinydict.values())#outputs dict_values(['John', '6000', 'zendaya'])
Enter fullscreen mode Exit fullscreen mode

or

my_dict={1:'name', 2:'age'}
print(my_dict)#ouputs {1:'name', 2:'age'}
Enter fullscreen mode Exit fullscreen mode

changing and adding values in a dictionary is done using the keys.

tinydict['code']=  7000#changes the element to 7000
print(tinydict)
tinydict[4]='casie'# adds a new pair entry
print(tinydict)
Enter fullscreen mode Exit fullscreen mode

*deleting values
*

del tinydict['name']#deletes the element with that value
print(tinydict) #outputs {'code': 7000, 3: 'zendaya', 4: 'casie'
tinydict.pop(4)  #removes element with that value
print(tinydict)#outputs{'code': 7000, 3: 'zendaya'}
Enter fullscreen mode Exit fullscreen mode

Accessing the elements is done using the keys

print(tinydict['code']) #outputs element with key ''code
Enter fullscreen mode Exit fullscreen mode

Sets

A set is a collection which is unordered, unchangeable(but you can remove items and add new ones),unique and unindexed.They are created using the flower braces.

myset={3,3,3,4,4,5,5,5,23,34,23,65,56,77}
print(myset)#outputs{65, 34, 3, 4, 5, 77, 23, 56}
Enter fullscreen mode Exit fullscreen mode

note that in sets, you will only output one of duplicate characters.

add elements
you can only add one element at a time.

my_set.add('zendaya')
print(my_set)#outputs {65, 34, 3, 4, 5, 77, 'zendaya', 23, 56}
Enter fullscreen mode Exit fullscreen mode

manipulate sets

  • The union() function joins the data from both sets.
  • The intersection() function only returns data that is present in both sets.
  • The difference() function deletes data from both sets and outputs data from only the set passed.
  • The symmetric difference() function performs the same operation as the difference() function, but it outputs the data that is still present in both sets.
my_set={65, 34, 3, 4, 5, 77, 'zendaya', 23, 56}
print(my_set)
my_set2={3.142,33,44, 3,3,5,5, 4,56, 'new zendaya', 'zendaya'}
print(my_set2)
#manipulating sets
print(my_set.union(my_set2))#outputs {'zendaya', 65, 34, 3, 4, 5, 33, 3.142, 44, 77, 'new zendaya', 23, 56}
print(my_set.intersection(my_set2)) #outputs {'zendaya', 3, 4, 5, 56}
print(my_set.difference(my_set2))#outputs {65, 34, 77, 23}
print(my_set.symmetric_difference(my_set2))#outputs {33, 65, 3.142, 'new zendaya', 34, 44, 77, 23}
Enter fullscreen mode Exit fullscreen mode

**

2.USER-DEFINED DATA STRUCTURES**

Python users can create their own Data Structures, giving them complete control over their functionality. The most common Data Structures are Stack, Queue, Tree, Linked List, and so on, all of which are also available in other programming languages.

Queues
A queue is a linear data structure based on the First-In-First-Out (FIFO) principle, which states that the data in first will be accessed first. It is constructed using an array structure and includes actions that can be performed from both the head and tail ends of the Queue, i.e., front-back and back-to-head. En-Queue and De-Queue operations include adding and deleting components, as well as accessing them. Queues are used as Network Buffers to handle traffic congestion, and as Job Scheduling in Operating Systems, among other things.

Image description

Stacks
Stacks are linear data structures that work on the Last-In-First-Out (LIFO) principle, which means that data inserted last is the first to be accessed. It is constructed using an array structure and includes activities such as pushing (adding) elements, popping (deleting) elements, and only accessing elements from the TOP of the stack. This TOP is a pointer to the stack's current location. Recursive programming, reversing words, undo systems in word editors, and other applications employ stacks extensively.

Image description

Graphs
Graphs are used to store data in the form of vertices (nodes) and edges (connections) (edges). The most accurate representation of a real-world map can be found in graphs. They are used to discover the least path by calculating the various cost-to-distance between the various data points known as nodes.

Image description

Nested lists
Connected lists are linear Data Structures that are linked together via pointers rather than being stored sequentially. A linked list node is made up of data and a pointer named next. These structures are most commonly employed in image viewer, music player, and other applications.

Image description

Arrays vs Lists
With one exception, arrays and lists are the same structure. Lists allow for the storage of heterogeneous data elements, whereas Arrays only allow for the storage of homogeneous components.

Top comments (6)

Collapse
 
sarveshprajapati profile image
Sarvesh Prajapati

try to add code literals, that would look better rather than plain white texts..

my_list=[] #create an empty list
my_list=[1,3,4, 'example ',3.142]
print(my_list) #prints (1,3,4, 'example' , 3.142)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mainashem profile image
SHEM MAINA

is there a way to do that? because I was writing the code in pycharm and copying it from there

Collapse
 
wanguiwaweru profile image
Bernice Waweru • Edited

Hey. Add "python" after the backticks on the codeblock

Thread Thread
 
sarveshprajapati profile image
Sarvesh Prajapati

yup

Collapse
 
sarveshprajapati profile image
Sarvesh Prajapati

yeah you can add triple string literal

Collapse
 
brayan_kai profile image
Brayan Kai

Great Article here πŸ‘ŒπŸŒŸ , Keep up πŸ‘