Data Structures in Python

data structures in python

Data Structures in python

Python has the ability to create varied types of applications such as desktop, web, Artificial Intelligence, Data Science and much more. The creation of such applications is possible only through the usage of data. Timely access to the inefficiently stored data Data plays a significant role through the technique called Data Structures.

What is Data Structure in Python?

Data structure refers to the process of manipulating the data. This manipulation process is inclusive of managing, organizing and storing the data in several ways. It is quite easier to obtain and modify the data. The data structure permits the storage of data, its modification and also allows to compare the data to others. It also allows to carry out some operations based upon the data.

Data Structures in python are of the following types:

In general, all the programming languages allow programming for these data structures. However, Python also comprises of certain in-built operations to do so. Data structures in Python have been typically divided into two types which are as follows:

  • Built-in Data Structures

  • User-Defined Data Structures

Built-in Data Structures

Python comprises of certain built-in data structure concepts for accessing and storing the data. The Built-in Data structures also known as implicit data structures in Python are as follows:

  • List

  • Tuple

  • Dict

  • Set

The above listed four data structure types are referred to as built-in data structures in Python. These data types are inculcated with predefined methods for manipulation of data such as accessing, storing as well as related operations.

List:

The collection of elements with duplicates is referred to as the list and is also known as ordered collection because it returns the elements in the same order as it has been inserted. The list follows the index-based storage to get the elements arranged in order and these aren’t supposed to be necessarily homogeneous i.e. storage of similar kinds of values. However, one can also store varied types of elements. These can be muted allowing us to manipulate the elements such as removing, adding and changing the values.

Creating a list:

The list can be created by making use of the square brackets as well as the list constructor. Since the list is mutable, therefore it can also be empty however, one can add the elements later.

Example:

my_l1=[]

print(my_l1)

my_l2=[1,2.5,’hello’]

print(my_l2)

my_l3=list([1,2,3,4,5])

print(my_l3)

Output:

[]

[1,2.5,’hello’]

[1,2,3,4,5]

Adding the Elements

You can make use of the following methods to add the elements:

  • append() – This method is used for placing the elements at the end of the list.

  • insert() – This method is also used for adding elements in the list. This method helps in placing the elements in the specific index and not at the end.

  • extend() – It is used to adds the list of elements to another list.

Example:

l=list()

l.append (10)

l.append(20)

l.append (30)

l.append(20)

print(l)

l.insert (3,40)

print(l)

l2=[50,60]

l.extend (l2)

print(l)

Output:

[10,20,30,20]

[10, 20, 30, 40, 20]

[10, 20, 30, 40, 20, 50, 60]

Deleting the Elements

Following method is used for deleting the elements in the list:

  • remove() – It is used for the removal of a specific element from the list.

  • pop() – This method straight away removes the last element from the list. If in case you manage to pass the index as a parameter then it would help in removing the element from the index.

  • clear() – This method helps to clear all the elements, present the list.

  • del – In order to remove the specified index element within a list, this keyword is used.

Example:

l=[1,2,3,4,5]

print(“List:”,l)

del l[3] print(“after del:”,l)

l.remove(3)

print(“after remove”,l)

l.pop()

print(“after pop”,l)

l.clear() print(“after clear”,l)

Output:

List:[1,2,3,4,5]

After del : [1,2,3,5]

After remove: [1,2,5]

After pop:[1,2]

After clear: []

Accessing the Elements:

The elements in the list are accessed on the basis of index value. Apart from this we also make use of some of the slicing concepts for accessing the values in the list.

Example:

l1=[1,2,3,4,5]

print(l1[3]) # it will return 3 indexed element as 4.

print(l1[:]) # it will return all the elements in a list

print( l1[1:])# it will return the elements from index 1.

print(l1[:3])# it will return the elements upto index 3.

print(l1[-1:]) # it will return the last element.

print(l1[:-1]) # it will return the elements upto -1 i.e last element.

Output:

4

[1, 2, 3, 4, 5]

[2, 3, 4, 5]

[1, 2, 3]

[5]

[1, 2, 3, 4]

Other Methods:

In addition to the above methods list uses the following methods for the processing of some of the operations:

  • index() – This method aims to return the index value of a specific element.

  • count() – For a specified element, this method aims to return the number of occurrences.

  • copy() – It helps in returning all the elements of one list to another list.

  • reverse() – It is used for reversal of the element’s index to the list.

  • sort() – It helps in the sorting of the elements of a specified list in ascending order.

  • len() – It is used for returning the number of elements within the list.

Example:

l=[1,3,2,5,4,5]

print(l.index(3)

print(l.count(5)

l1=l.copy()

print(l1)

print(len(l1))

l.reverse()

print(l)

l.sort ()

print(l)

Output:

1

2

[1,3,2,5,4,5]

6

[5, 4, 5, 2, 3, 1]

[1, 2, 3, 4, 5, 5]

Dictionary

Dictionary refers to the mutable collection used for storing the elements in a key-value pair. For example, a college comprises of thousands of students and in case we identify the students as per their names then there are fair chances of coming across similar names. Thus, in such a scenario, the college administration makes use of the registration number to identify such kind of element stored within a dictionary because the dictionary stores the registration number of the students as key and their name as the value. Dictionary doesn’t permit the duplicate keys and based on that the student registration number is also a unique one.

Creating a Dictionary

Dictionary is generally created by using the object and can also be created using the curly braces. Each element of the dictionary is identified as key and value pairs. Similar to the lists, the dictionary can also be created empty i.e. with no elements in it.

Example:

m_dict={}

print(m_dict)

m_dict1={‘a’:”apple”,’b’:”banana”}

print(m_dict1)

Output:

 

{]

{‘a’:” apple”,’b’:” banana”}

Adding and Changing the Elements:

Just like the index in the list, to carry out the operations, the dictionary always makes use of the key. In order to add the elements within the dictionary, you may make use of the key-value pair. Your wish to change or override the value also depends on key only.

Example:

<m_dict1={‘a’:”ant”,’b’:”banana”}

print(m_dict1)

m_dict1[‘c’]=”cat” # add the element to the dictionary

print(m_dict1)

m_dict1[‘b’]=”bee” # changing the value of the element using key

print(m_dict1)

Output:

{‘a’: ”ant”, ’b’ : ”banana”}

{‘a’:”ant” , ‘b’ : “banana” , ‘c’: “cat”}

{‘a’:”ant” , ‘b’ : “bee” , ‘c’: “cat”}

Deleting the elements:

The following methods are used for deleting the elements within the dictionary.

  • pop() – It is used for removing the element within the specified key value.

  • Pop item() – It is used for removing the first set of key-value pairs within the dictionary. It also helps in returning the elements within a tuple.

  • clear() – it is used for clearing the all key-value pair of the elements.

Example:

m_dict = {‘a’:”ant” , ‘b’ : “bee” , ‘c’: “cat”}

print(m_dict)

print(m_dict.pop(‘c’))

print(m_dict.popitem())

m_dict.clear ()

print(m_dict())

 

Output:

 

{‘b’: ‘bee’, ‘c’: ‘cat’, ‘a’: ‘ant’}

‘cat’

(‘b’, ‘bee’)

{}

Accessing the Elements:

In order to access the elements of the dictionary is done by using keys just like the index in the list and additionally, we may also use the method called get(). In order to receive the element value just pass the key as the parameter.

Example:

m_dict = {‘a’:”ant” , ‘b’ : “bee” , ‘c’: “cat”}

print(m_dict)

print(m_dict[‘b’])

print(m_dict.get(‘c’))

Output:

{‘b’: ‘bee’, ‘c’: ‘cat’, ‘a’: ‘ant’}

bee

cat

Other Functions:

In addition to the manipulation methods listed above, the following are various other methods in the dictionary:

  • Items() – This method helps in returning all the key-value pairs of elements within the list of tuples.

  • keys() – This method is used to return only the keys as a list.

  • values() – This method would help in returning the values as a list.

Example:

m_dict = {‘a’:”ant” , ‘b’ : “bee” , ‘c’: “cat”}

print(m_dict)

print(m_dict.items())

print(m_dict.keys())

print(m_dict.values())

Output:

{‘b’: ‘bee’, ‘c’: ‘cat’, ‘a’: ‘ant’}

dict_items([(‘b’, ‘bee’), (‘c’, ‘cat’), (‘a’, ‘ant’)])

dict_keys([‘b’, ‘c’, ‘a’])

dict_values([‘bee’, ‘cat’, ‘ant’])

tuple:

A tuple refers to the immutable collection of elements i.e. once the elements enter the tuples they can’t be changed otherwise it would just look like a list in python.

Creating a tuple

Tuple can be created by making use of a tuple constructor or parenthesis.

Example:

my_t=(1,2,3,4)

print(my_t)

Output:

(1,2,3,4)

Accessing Elements:

Example:

my_t=(1,2,3,4)

print(my_t)

for i in my_t:

  print(i)

print(my_t[2])

print(my_t[:])

Output:

(1,2,3,4)

1

2

3

4

3

(1,2,3,4)

Appending Elements:

In order to add the elements to a tuple, the symbol + is used. It just helps in the concatenation of the tuples of values.

Example:

my_t=(1,2,3,4)

my_t1=(7,8,9)

my_t=my_t+my_t1

print(my_t)

Output:

(1,2,3,4,7,8,9)

 

Other Functions

Tuple do not allow any manipulation method as it is considered to be an immutable collection of values. Thus, it uses only the following methods-

  • count() – It is used to return the number of occurrences of a specific element.

  • index() – It is used to return the position of the specified element.

 

Example:

my_t=(1,2,3,2)

print(my_t)

print(my_t.count(2))

print(my_t.index(3))

Output:

(1,2,3,4)

2

2

Sets

Sets in Python refer to the unordered collection of the elements and do not allow duplicates i.e. if one tries to insert the same element more than once, it won’t accept i.e. it takes that particular element only once. This specific set of operations are similar to the arithmetic sets in mathematics.

Creating a Sets

Sets in python can be created by using curly or flower braces. It contains unique values as it doesn’t allow duplicates.

Example:

my_s={1,2,3,4,3,5,2}

print(my_s)

Output:

{1,2,3,4,5}

Adding Elements

Use add() method to add the elements in the sets.

Example:

my_s={1,2,4,2}

my_s.add(3)

print(my_s)

Output:

 

{1,2,3,4}

Other Operations in Sets

The following are the various operation methods of the sets.

  • union() – This method is used for performing the unit operations of the set. The two sets can be simply concatenated without duplicates.

  • intersection() – This method helps to return the common values of both sets.

  • difference() – This method helps to return the difference values within the passed set. Additionally, it also deletes the data that is present in both sets.

  • symmetric_difference() – This method is used for returning a similar process of difference() method. But it would return the data that remains in both the sets.

Example:

my_s1={1,2,3,4}

my_s2={3,4,5,6}

print(my_s1.union(my_s2))

print(my_s1.intersection(my_s2))

print(my_s1.difference(my_s2))

print(my_s1.symmetric_difference(my_s2))

Output:

{1,2,3,4,5,6}

{3,4}

{1,2}

{1,2,5,6}

 

User-Defined Data Structures

The user-defined data structure is obtained using writing based on their algorithm logic and is not an in-built function or predefined data structure type. The same is true for all languages and thus it is implemented in python programming language too. Following are the user-defined data structures in Python-

  • Stack

  • Queue

  • Tree

  • Linked list

  • Graph

  • HashMaps

 

Before we begin with the user-defined data structures, we must understand the existing variation between the arrays and the list. Arrays are not dynamic in nature and are primarily used to store homogenous data into it while the list in python is dynamic in nature and is used to store heterogeneous data.

Stack

Followed by virtual memory, the stack is a basic data structure concept and is a linear data structure type. In the order of Last In First Out process i.e. LIFO, it is followed to manipulate data. For the purpose of storing and retrieving the variables, the programming language memory managements would follow this data structure type. The stack comprising of few of the manipulation processes such as the addition of the elements called as pushing, removal of the elements known as popping and also access the elements. That is known as a TOP element which makes use of the cursor to point out the TOP element i.e. the current element in the stack. This cursor moves one by one, once you pop the elements. Stack mostly makes use of the recursive process and reverses the process.

Queue:

Similar to the stack, Queue is also a linear data structure type that follows the process of First In First Out i.e. FIFO. Unlike the stack, the case is opposite here, i.e. the element that has been inserted first will be popped out first whereas, in the stack as per LIFO, the last inserted element will pope out first. The queue is created with the help of an array of elements as well as operations that are done at both the ends of the queue such as head-tail or front-back of the process. We possess two kinds of a queue here i.e. en-queue and deque. These two queues are used depending on the operations like adding and removing elements. The queue is majorly used in OS for scheduling of jobs and it is also used in network buffer management in case of traffic congestion and more.

Tree:

A tree in python is referred to as a kind of non-linear data structure. It helps in the storage of the elements within a tree structure such as parent and child node process and also follows the root as well as nodes. The root will be the beginning element and nodes would be the other data stored points. A tree comprising of different levels symbolizes the depth of the information. The last node is also known as leaves. A tree finds its use for efficiency in searching and much more. It is also used for the creation of the website by making use of HTML in order to identify the enclosed tags.

Linked List:

The linked list falls under the linear data structure type and it stores the elements based on the nodes. Every node comprises of the data as well as the address for the next node. The data present in the linked list has not been stored inconsequently. This kind of data structure is mostly used in music player applications as well as image view applications. These are also of different types like doubly, circular.

Graph:

Graphs represent the data stored in the collection with vertices (i.e. nodes ) as well as edges. These graphs hold advantage in order to show the data accuracy in real-world maps. These graphs are generally used to find the least path i.e cost-to-distance amongst the data points also known as nodes. It is mostly utilized in map-related applications such as ola, uber, google maps to find the shortest distance for better performance.

HashMaps:

HashMap is used for storing the data in key-value pairs such as a dictionary in python. Such kinds of data structures are majorly used for storing student details, grocery details, phone books, storing as well as populating the data to list and even more.

Python Training in Noida

If you wish to gain expertise in the skills of Python programming techniques then opt for APTRON’S Python Training in Noida. The institute applies a unique training methodology and Python course content is designed as per the industry recommendations. This, in turn, prepares the students as per the industry standards. The Python training in Noida at APTRON involves more of the practical sessions while training the students on real-time Python projects for them to get the best knowledge of the subject. Industry expert corporate Python professionals conduct the classes for the Python course in Noida at APTRON. Extensive infrastructure with highly advanced and high-tech lab facilities gives the students an excellent learning environment. Also, the duration for the Python training in Noida at APTRON class is flexible with batches running both in the daytime and evening during weekends and weekdays and also fast-track Python course in Noida are available here. APTRON is the best Python training institute in Noida as the training here is accompanied by 100% placement assistance to each attendee.

Best Training Institute for IT Course Enquiry

Please Fill This Form To Get Best Training Institute for IT Course Information

X
QUICK ENQUIRY