Data Structures with Python

profile Dhairya

The meaning of Data Structure is clear with the word itself, the organization of data. But Data Structures with Python is altered from Data Structure you might have studied in other languages. Languages like C, C++, Java, etc. have different Data Structures like Arrays, Linked Lists, Stack, Queue, Tree, and Graph.

These data structures are included in Python as well. Additionally, for the ease of the programmer, Python has some Built-in Data Structures also. These are known as List, Tuple, Sets, and Dictionaries. In this blog, we will cover the built-in Data Structure with Python.

If you don't know what is data structures you can check my blog by clicking on What is Data Structures

List

Python Lists are the containers to store a set of values of any data type. A list is defined in square brackets where the elements are separated by commas.

Every string of the list is enclosed in single inverted commas 'string', and the elements other than string are not stored in inverted commas. A list is always an ordered list and it is mutable that is we can add or remove the elements whenever and wherever we wish to add.

Syntax of defining  a List: 

L = [ e1, e2,e3...,en], where e1, e2...en represent the elements of List

L = ['Apple', 165, True]
print(L)

Output

['Apple', 165, True]

List Methods

There are various methods of List that help in performing different operations. We will see some commonly used List Methods here.

1. Sort()

 The first List Method is the sort method, which is used to arrange the elements of a list in a particular order.

Syntax: L.sort()

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)        #print the list
L1.sort()        #sort the list
print(L1)        #print the list after sorting

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']   #the actual list
['Apple', 'Apple', 'Banana', 'Grapes', 'Mango']   #the sorted list

2. Reverse()

It is used to reverse the elements of the given list. The element at the last will appear at the first and vice versa.

Syntax: L.reverse()

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)           #print the list
L1.reverse()        #sort the list
print(L1)           #print the list after sorting

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']   #the actual list
['Mango', 'Grapes', 'Banana', 'Apple', 'Apple']   #the reversed list

3. Append(element)

 This method is used to add the element at the end of the list, as a list.

Syntax: L.append(e)

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)                   #print the list
L1.append('Pineapple')
print(L1)                   #print the appended list

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
['Apple', 'Mango', 'Banana', 'Apple', 'Grapes', 'Pineapple']

4. Extend(element)

This is used to add the element at the end of the list, as a separate element.

Syntax: L.extend(e)

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)                   #print the list
L1.extend('Pineapple')
print(L1)                   #print the extended list

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
['Apple', 'Mango', 'Banana', 'Apple', 'Grapes', 'Pineapple', 'P', 'i', 'n', 'e', 'a', 'p', 'p', 'l', 'e']

5.Remove()

It is used to pass an object to remove from the list (instead) of the index, pass the element that you want to remove.

Syntax: L.remove(e)

Note: If the element you wish to remove appears more than once in a list, it will remove the first element.

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)        #print the list

L1.remove('Apple')
print(L1)        #prints the list after removing the element 'Apple' at index[0]

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
['Mango', 'Banana', 'Apple', 'Grapes']

6. Pop()

 This function helps to remove the last element from the list.

Syntax: L.pop()

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)        #print the list

L1.pop()
print(L1)        #deletes the element 'Grapes' from the list

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
['Apple', 'Mango', 'Banana', 'Apple']

7. Clear()

This function of Data Structures with Python will clear all the elements from the list.

Syntax: L.clear()

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)        #print the list

L1.clear()
print(L1)       #prints the empty list

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
[]

8. Del Keyword

Del is a pre-defined word in Python. It helps to remove the element at a particular index.

Syntax: del L[index]

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)        #print the list

del L1[0]
print(L1)        #prints the list after deleting the element at index[0]

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
['Mango', 'Banana', 'Apple', 'Grapes']

9. Count()

Count function will display the number of times an element appears in the list.

Syntax: L.count(e)

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)                  #print the list

print(L1.count('Apple'))   #displays the number of times an element appeared

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
2

10. Insert()

 This function will insert an element at a particular index.

Syntax: L.insert(index,element)

L1 = ['Apple','Mango','Banana','Apple','Grapes']
print(L1)                   #print the list

L1.insert(1,'Pinepapple')   #insert the element at index 1
print(L1)                   

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
['Apple', 'Pinepapple', 'Mango', 'Banana', 'Apple', 'Grapes']

Tuples

Tuples are also used to store values of a data type as a list. The difference between tuple and list is that tuple is used to store the values of the same data type only. Tuples are defined using round brackets ().

Items of the tuple are ordered and immutable. You cannot change the elements of a tuple once they are defined. Tuples accept duplicate values, You can use the same value at different indexes.

Syntax of defining a Tuple:

T = (e1, e2, e3..., en), where e1, e2...en represent the elements of Tuple

T = ['Apple','Mango','Banana','Apple','Grapes']
print(T)

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']

Tuple Methods

We do not have many tuple methods as in the list, because we cannot add or remove the elements in a Tuple as the Tuples are immutable.

1. Count()

This method works the same as in List. It will return you the number of times an element appeared in the Tuple.

Syntax: T.count("element")

T = ['Apple','Mango','Banana','Apple','Grapes']
print(T)             
print(T.count("Apple"))   #return the number of times "Apple" appeared in the Tuple

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
2

2. Index

The Index method of Data Structures with Python will search for the tuple for the given value and returns the position where it is found. If the specified element appears more than once, then it will return the value where the element appears first.

Syntax: T.index("element")

T = ['Apple','Mango','Banana','Apple','Grapes']
print(T)
print(T.index("Apple"))

Output

['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']
0
Is there any way to Modify the Tuple?

Yes, you can modify a tuple, but you need to convert the Tuple into a List. And after modifying you need to convert the List back into the Tuple.

To convert a list into a Tuple List() function is used and to convert the List into a Tuple, the tuple() function is used. Here is an example to convert the modify the Tuple. 

T = ['Apple','Mango','Banana','Apple','Grapes']
print(T.sort())        #this statement will print the elements in Round Brackets

list1 = list(T)
print(list1)           #this statement will print the elements in Sqaure Brackets as a List

Output

('Apple', 'Mango', 'Banana', 'Apple', 'Grapes')    #result of print(T.sort())
['Apple', 'Mango', 'Banana', 'Apple', 'Grapes']    #result of print(list1)

In the above example, you have seen how a list is converted to a tuple. Similarly, a tuple is converted into a list by using the tuple() function.

Sets

The next Data Structures with Python is Sets. Sets are a collection of non-repetitive elements. They are defined using curly braces {}.

Properties of Sets.

1. Sets are unordered, you can't expect in which order the elements are arranged in output.

2.They are unindexed, you can't access the elements by their indexes.

3. Sets are immutable, you can't change the elements once they are arranged.

4. It doesn't accept duplicate values.

Syntax of defining a Set:

S = {e1, e2, e3,...,en}, where e1, e2 represent the elements of Set.

S = {1, 8, 23, 56, 12}
print(S)

Output

{1, 8, 12, 23, 56}

Sets Methods

You have studied the sets methods before also. We will now implement these methods here in Data Structures with Python. Let's see what are these methods

1. Union()

Union function is used to join the two different or same sets together. 

Syntax: S1.union(S2), where S1 and S2 are two sets

S1 = {1, 8, 23, 56, 12}
S2 = {4, 76, 45, 67, 85, 98}
print(S1.union(S2))

Output

{1, 98, 67, 4, 8, 12, 76, 45, 85, 23, 56}

2. Intersection

The intersection is used to find the common elements in the given two sets.

Syntax: S1.intersection(S2)

S1 = {1, 8, 23, 56, 12}
S2 = {4, 76, 45, 67, 85, 98}
print(S1.intersection(S2))

Output

set()    #when no elements are common between two sets

3. Difference

This method is used to get the elements present in Set1 and not in Set2.

Syntax: S1.difference(S2)

S1 = {1, 8, 23, 56, 12}
S2 = {4, 76, 45, 67, 85, 98}
print(S1.difference(S2))

Output

{1, 8, 12, 23, 56}

Dictionaries

Dictionary is a collection of Key-Value pairs. The dictionaries are also defined with the same braces as sets, that is curly braces {}.

Properties of Dictionaries:

1. Dictionaries are unordered, they don't know how the output elements will be arranged.

2. These are mutable, you can easily change the elements of Dictionaries.

3. You can access the elements using the index, that is Dictionaries are indexed.

4. The keys cannot be duplicated in a dictionary, values can be mutable and duplicate.

Syntax of a Dictionary:

d = {"key" : "value"}

d = { 'language' : "python", "topic" : "data structure", "subtopic" : "dictionaries"}
print(d)

Output

{'language': 'python', 'topic': 'data structure', 'subtopic': 'dictionaries'}

Dictionary Methods

Dictionary Methods will help you to easily find the key: value pair that you need. You can update the dictionary according to your needs and wants.

1. Items()

Items method will display the dictionary items in an intelligible manner.

Syntax: d.items()

d = { 'language' : "python", "topic" : "data structure", "subtopic" : "dictionaries"}
print(d)
print(d.items())

Output

{'language': 'python', 'topic': 'data structure', 'subtopic': 'dictionaries'}
dict_items([('language', 'python'), ('topic', 'data structure'), ('subtopic', 'dictionaries')])

2. Keys()

The Keys method is used to get all the keys of the dictionary.

Syntax: d.keys()

d = { 'language' : "python", "topic" : "data structure", "subtopic" : "dictionaries"}
print(d)            #prints the complete dictionary
print(d.keys())     #prints the keys of the dicitonary

Output

{'language': 'python', 'topic': 'data structure', 'subtopic': 'dictionaries'}
dict_keys(['language', 'topic', 'subtopic'])

3. Get()

This method is used to get the value of the specified key. 

Syntax: d.get("key")

d = { 'language' : "python", "topic" : "data structure", "subtopic" : "dictionaries"}
print(d)                    #print the dictionary
print(d.get("topic"))       #print the value of the key "topic"

Output

{'language': 'python', 'topic': 'data structure', 'subtopic': 'dictionaries'}
data structure

4. Update()

The update method is used to modify the dictionary. You can add more keys with their values in the dictionary.

Syntax: d.update("key":"value")

d = { 'language' : "python", "topic" : "data structure", "subtopic" : "dictionaries"}
print(d)
d.update({"sub topic":"data structures with python"})
print(d)              #prints the updated dictionary

Output

{'language': 'python', 'topic': 'data structure', 'subtopic': 'dictionaries'}
{'language': 'python', 'topic': 'data structure', 'subtopic': 'dictionaries', 'sub topic': 'data structures with python'}

5. Pop()

The pop method will remove the element with the specified key.

Syntax: d.pop("element")

d = { 'language' : "python", "topic" : "data structure", "subtopic" : "dictionaries"}
print(d)
d.pop("language")     #remove the key: value pair of the key "language"
print(d)          

Output

{'language': 'python', 'topic': 'data structure', 'subtopic': 'dictionaries'}
{'topic': 'data structure', 'subtopic': 'dictionaries'}

Conclusion

Here are the different Data Structures with Python, with their methods. I hope you liked the blog, your valuable suggestions and feedbacks are always welcomed. You can comment below to share your views. 

Related Blogs

Also Read

Subscribe Us

* indicates required

Dhairya

I am a student of Bachelor of Computer Applications. I love to research and write … readmore