Python & Backend
Apr 16, 2022
11 min read
Inbuilt data structures in Python
Introduction
Data Structures are a way of organizing and storing data in a way so that it can be used efficiently. Knowing inbuilt data structures of any language can save you a lot of time and help you decide better which one to use according to the nature of data. In this blog, I will discuss some of the important data structures in python and their common operations. 🙂
List
List is an ordered collection of items which are changeable, and it allows duplicates.
1. Create a list
There are two ways to create a list in python.
empty_list = []
marks_list = [98, 92, 93, 91]
print(empty_list)
print(marks_list)
- Call python list built-in function. Syntax:-
list(iterable). Iterable is an object which you can loop over like lists, tuples, sets, dictionaries, strings etc.
empty_list = list()
marks_list = list((98, 92, 93, 91))
print(empty_list)
print(marks_list)
Output:-
[]
[98, 92, 93, 91]
2. Find length of a list
Python has a built-in function len which can be used to find length of a list.
marks = [99, 95, 93, 98]
list_length = len(marks)
print(list_length)
Output:- 4
3. Access element in a list
List items can be accessed by using the syntax:- list[index]. Negative index can be used to find the element in reverse order.
- list[-1] -> returns the last element in the list.
- list[-2] -> returns the second last element in the list. and so on.
fruits_list = ['apple', 'banana', 'orange', 'mango']
print(fruits_list[2])
print(fruits_list[-1])
print(fruits_list[-3])
Output:-
orange
mango
banana
4. Add element to a list
a. using append() — adds an element to the end of the list. Syntax:- list.append(item_name)
subjects = ['Maths', 'Physics', 'Chemistry']
subjects.append('Biology')
print(subjects)
Output:- ['Maths', 'Physics', 'Chemistry', 'Biology']
b. using insert() — adds an element at a specified position. Syntax:- list.insert(index, item_name)
subjects = ['Maths', 'Physics', 'Chemistry']
subjects.insert(1, 'Biology')
print(subjects)
Output:- ['Maths', 'Biology', 'Physics', 'Chemistry']
5. Modify element in a list
fruits_list = ['apple', 'banana', 'orange', 'mango']
fruits_list[1] = 'guava'
print(fruits_list[1])
Output:- guava
6. Remove element from the list
a. using del — deletes the value at the specified index and does not return any value.
subjects = ['Maths', 'Physics', 'Chemistry', 'Biology']
del subjects[1]
print(subjects)
Output:- ['Maths', 'Chemistry', 'Biology']
b. using pop — deletes the value and returns the deleted value. list.pop() deletes the last element; list.pop(index) deletes at a specified index.
c. using remove — removes an element by value, not by index. If the value is not present, it raises a ValueError.
subjects = ['Maths', 'Physics', 'Chemistry']
subjects.remove('Physics')
print(subjects)
Output:- ['Maths', 'Chemistry']
d. using clear — removes all the elements from the list.
subjects = ['Maths', 'Physics', 'Chemistry']
subjects.clear()
print(subjects)
Output:- []
7. Looping through the list
numbers = [5, 6, 3, 22]
for number in numbers:
print(number)
Important Note:- A python list can contain items of any type:- list, set, tuples, dictionaries, numbers, strings.
sample_list = [1, 'food', [2, 4, 6], {"set_element1", "set_element2"}, {"blog_name": "python DS"}, (1, 2)]
for element in sample_list:
print(type(element))
Output:-
<class 'int'>
<class 'str'>
<class 'list'>
<class 'set'>
<class 'dict'>
<class 'tuple'>
Set
Set is an unordered collection of items which does not allow duplicates. A set itself is mutable since we can add and remove elements, but the elements it consists of must be immutable.
1. Create a set
Using curly {} brackets:
marks_set = {98, 92, 93, 91}
print(marks_set)
We cannot create an empty set using {} brackets, as it would default to a dictionary. We can use set() to create an empty set.
empty_set = set()
numbers_set = set((98, 92, 93, 91))
print(empty_set)
print(numbers_set)
Output:-
set()
{98, 91, 92, 93}
2. Find length of a set
numbers = {99, 95, 93, 98, 95}
print(len(numbers))
Output:- 4
3. Access element in a set
Since set elements are unordered, python does not provide a method to access an element at some index. But we can check whether an element is present using the in operator.
fruits_set = {'apple', 'banana', 'orange', 'mango'}
if "apple" in fruits_set:
print("Apple is present")
else:
print("Apple is absent")
4. Add element to a set
We can simply add an element to a set, but can't guarantee at which position it would go. Syntax:- set.add(element)
subjects = {'Maths', 'Physics', 'Chemistry'}
subjects.add('Biology')
print(subjects)
5. Remove element from the set
a. using pop — deletes and returns a value (since unordered, you may get a different element each run).
b. using remove — removes by value, raises a KeyError on an invalid value.
c. using discard — like remove, but does not raise an error on an invalid value.
d. using clear — removes all elements.
subjects = {'Maths', 'Physics', 'Chemistry'}
subjects.discard('Physics')
print(subjects)
Output:- {'Chemistry', 'Maths'}
Important Note:- Since elements in a set cannot be changed, they can be numbers, strings, and tuples, but cannot be lists or dictionaries or sets. i.e only immutable elements are allowed in a set.
Dictionary
It is a collection of key-value pairs. A key must be immutable like strings, numbers, tuples. Keys are unique in a dictionary. A value can be anything (strings, numbers, tuples, list, sets, dictionary).
1. Create a dictionary
empty_dict = {}
subj_marks_dict = {
"Maths": 98,
"Chemistry": 92
}
print(subj_marks_dict)
Or call the python dict built-in function:
subj_marks_dict = dict([("Maths", 98), ("Chemistry", 92)])
print(subj_marks_dict)
2. Access element in a dictionary
Dictionary items can be accessed using the syntax:- dict[key]. If the key is not valid it throws a KeyError. The get method doesn't throw an error on an invalid key — instead it returns None (or a default you pass as the second argument).
student = {
"name": "Student1",
"college": "IIT Roorkee",
"hobbies": ['pool', 'blogging'],
"gender": "male"
}
print(student["name"])
print(student.get("branch"))
print(student.get("branch", "Mechanical"))
Output:-
Student1
None
Mechanical
3. Add / Modify / Remove
A new element can be added by assigning a new key-value pair: dict[key] = value. Modify by assigning a new value to an existing key. Remove with del dict[key], or remove everything with clear().
4. Looping through the dictionary
for key, value in student.items():
print(key, ":", value)
for key in student.keys():
print(key)
for value in student.values():
print(value)
Important Note:- Python dictionary keys must be immutable while values can be any type. The key-value pairs are kept in insertion order (since Python 3.7), unlike a set where elements are unordered.
Tuple
A tuple in python is an immutable list — that means we can't add, modify or delete values from the tuple. As a result, we don't have any of the mutating operations we see in a list.
Why use a tuple? A tuple is very useful when we want to create a list that we don't want to change. A tuple can prevent accidental modification, deletion or addition.
1. Creating a tuple
even_numbers = (2, 4, 6, 8, 10)
print(even_numbers)
Or call the python tuple built-in function. Syntax:- tuple(iterable)
even_numbers = tuple([2, 4, 6, 8, 10])
print(even_numbers)
2. Find length of a tuple
even_numbers = (2, 4, 6, 8, 10)
print(len(even_numbers))
Output:- 5
3. Access element of a tuple
Tuple items can be accessed by using the syntax:- tuple[index]. Negative index can be used to find the element in reverse order.
even_numbers = (2, 4, 6, 8, 10)
print(even_numbers[0])
print(even_numbers[-1])
Output:-
2
10
4. Looping through the tuple
numbers = (5, 6, 3, 22)
for number in numbers:
print(number)
Important Note:- A python tuple, similar to a list, can contain items of any type:- list, set, tuples, dictionaries, numbers, strings.