Data Structures in python are used to store organised data.Your programs are almost built around data structures so that you can work effectively and efficiently with the data.The data structures are categorized into primitive data structures, built in data structures and user defined data structures.
Primitive data structures
These are the basic data structures, including ,integer , float , string and boolean ,which contain pure and simple forms of data.
# Example for Integer x =3 y =3 print(x / y ) # Example for FLoat x = 3.5 y =3.5 print(x + y) # Example for String x = ‘True’ y = ‘False’ print(x + y) # Example for Boolean x = True y = False print(x == y) |
The above will have an integer result as
1 7.0 TrueFalse False |
User Defined data structures
The various other user defined data structures include stack, queue,tree, linked list,hashmaps.
Stack
It is a linear data structure, which follows the principle of Last In First Out ‘.An example of stack could be your favourite books arranged on the table one above the other. You would add the most favourite book at the end (on the top), so that you can get it first.The first or the top element acts as a pointer for the current element in the stack.
Elements can be added on the top with a push, removed from the top with a pop. The length of the stack can be found with len method.
A real world implementation of stack could be the undo function.The word processor keeps record of the previous actions on stack so that the last action is on top, and you can always go to the last action performed with the undo function.
Queue
This is also a linear data structure with the principle of First In First Out or Last In Last Out. In a waiting line, the first person in the line will be served first and the new person at the last.
The elements in the queue can be added with enqueue and removed with the deque.Both these operations take O(1) time irrespective of the number of elements present in the queue.
Real world implementation of queues can be found in the network buffers and operating systems for job scheduling etc.
Trees
These are non linear data structures with nodes(vertices) and root.The root is the origin from where the nodes or vertices begin, therefore a node is a child for which root or node it comes from,and the preceding one is the parent.Leaves are the last nodes or the nodes without children.
A family tree could be the best example for the tree data structure.where the grandparents are the root and their children are nodes , and their children without any child are leaves
A real world implementation of trees could be found in the structure of html tags. The html is the root tag, and the ones that come after are the nodes.
Linked lists
These are the linear data structures which are connected to each other with a pointer called next.The nodes in the linked lists carries data and can be stored anywhere in the memory unlike lists or arrays which are stored sequentially.A train could be the best example for linked lists. It has a locomotive (head) that powers the engine, rail cars(nodes) which carry freight(data).Unlike lists, random access of data is not supported in linked lists.
A real world implementation of linked lists can be found when you are using multiple applications.
Graphs
Graphs are non linear data structures , with a collection of objects(called nodes or vertices) with links(edges) in between.
A real world implementation would be when you are trying to find the shortest path using Google Maps or Uber
Hash Maps
Hashmaps are the data structures where the data is stored in pairs or with each data there is an associative or mapped value.
Their applications can be found in storing phone numbers with names, storing items with prices etc.
Checkout this Online Python Training by FITA. FITA provides a complete Django course where you will be building real-time projects like Bitly and Twitter bundled with Python training.
Built-in data structures
There are 4 built-in data structures in python. They are Lists, sets, tuples and dictionaries.
Lists
Lists in python are dynamic arrays which can store a series of items in an ordered manner, that is the order in which they were defined will be retained unlike dictionaries and sets.Lists are mutable or changeable, that is you can add, remove or update items from the list.
Defining or Creating List
An empty list can be created with empty square brackets or with list method, aAnd add elements to it.
# Example for creating list t = [ ] # An empty python list y = [1,2,list,’with’,’values’] z = list() # empty list with list function print(t, y,z) |
The above program will have the output as,
[ ] [1,2,’list’,’with’,’values’] [ ] |
Adding Elements to list
# Example program for adding elements list list_1 = [ ] list_1.append(‘1’) list_1.append([2,3,4]) print(‘modified list: ’,list_1) list_1.extend([5,6,7]) list_1.extend([8]) print(‘modified list: ’,list_1) list_1.insert(1,’Hi there’) list_1.insert(1,’I am list’) print(‘modified list: ’,list_1) |
Which outputs
modified list: [1,[2,3,4]] modified list: [1,[2,3,4],5,6,7,8] modified list: [1,’I am list’,’Hi there’,[2,3,4],5,6,7,8] |
Accessing elements from the list
# Example program for accessing element from list lst_1 = [1,’Hi there’,’I am list’,2] lst_2 = [lst_1[0],lst_1[-1],lst_1[1],lst_1[-2]] print(‘first,last,second,second last elements from the lst_1 are: ’,lst_2) for i in lst_1: print(i, end=’ ‘) print(lst_1[1:3:1]) |
Output
first,last,second,second last elements from the array 1 are: [1,2,’I am list’,’Hi there’] 1 Hi there I am list 2 [1,’I am list’] |
Removing Elements from list
# Example program for removing elements from list x = [‘A’, ‘complete’,’python’, ‘tutorial’,’at’,’FITA’ ] x.pop() print(x) x.remove(‘python’) print(x) x.clear() print(x) |
Which outputs
[‘A’, ‘complete’,’python’, ‘tutorial’,’at’ ] [‘A’, ‘complete’, ‘tutorial’,’at’ ] [ ] |
The other various methods that can be applied to a list are, sorted,len, index,count etc.
Dictionaries
Dictionaries are used to store values in pairs, usually as key and its value. For example,
Storing name of persons as keys and their phone numbers as values.
# Example for creating dictionaries # an empty dictionary dict_1 = { } dict_2 = dict() dict_1 = {‘name’ :’rosy’,phone:1234} # dictionary with values print(dict_1,dict_2) |
Output
{‘name’ :’rosy’,’phone’:1234} { } |
dict_2[‘names’] = [‘rachael‘,’ruby’,] # adding new value dict_2[‘phone’] = [8520,7410] dict_1[‘phone’’] = 9876 # updating existing value print(dict_1,dict_2) |
Output
{ ‘name’: ’rosy’, phone:9876 } { ‘name’: [’racheal’,’ruby’], ’phone’: [8520,7410] } |
Other methods that can be applied on dictionaries,are get(),keys(),values(),items().
Tuple
Tuples are the same as lists except that they are immutable or unchangeable; that is their value once entered cannot be changed or updated or deleted.
# Example program for tuple #empty tuple tup_1 = () tup_1 += (1,2,3,) # adding elements to tuple # tup_1[1] = 2 this would give a type error x = tup_1[0] # accessing element from tuple print(tup_1) |
Output
(1,2,3) |
Sets
Sets in python are as same as sets you might have learned in high school mathematics.They are mutable and cannot have repeated values.sets are unordered,that is their order is not reserved after assigning values to them.The different operations that can be performed on sets includes union,intersection,difference, symmetric difference.
Sets are denoted with curly { } braces around values separated by commas.
# Example program for sets set_1 = { 2,3,4} # adding elements to sets set_1.add(4) set_1.add(1) print(set_1) # removing an elements from sets set_1.remove(3) print(set_1) # clearing the set set_1.clear() print(set_1) |
Output
{1, 2, 3, 4} {1, 2, 4} set() |
You might have noticed that the set function filtered the values to be unique.
# Example program for union operation on sets set_1 = { 2,3,4} set_2 = {‘python programming’} # union on sets print(set_1|set_2) print(set_1.union(set_2)) |
The above two print statements will have the same output as the unique elements in both the sets
{‘python programming’,2,3,4} |
# Example program for intersection operation on sets set_1 = set(‘2,3’) set_2 = set(‘python programming 2’) # intersection on sets print(set_1 & set_2) print(set_1.intersection(set_2)) |
The above two print statements will have the same output as the same elements in both the sets.
{‘2’} |
Similarly you can perform other functions like difference , symmetric difference etc.
This was all about built in data structures in python.Now let’s talk about user defined data structures in python.
This was all about data structures in python with its types and implementations and real world applications..To get in-depth knowledge of Python along with its various applications and real-time projects, you can enroll in Python Course in Chennai or Python Course in Bangalore by FITA at an affordable price, which includes real time projects with certification, support and career guidance assistance.