Introduction
As the name implies data structures are structures that hold some related data. Python has built-in data structures such as lists, tuples, dictionaries, and sets. These all data structures are used to store the data.
List
List is one of the built-in data structures available in python. It holds the sequence of data enclosed by a square bracket and separated by a comma.
How to create an empty list?
Lst = list()
There is another method to create an empty list
Lst = [] print(type(Lst))
Output
<class 'list'>
This is how we can create an empty list.
Adding elements to list
To add elements to an empty list we can use the append() function
Lst.append("ram") Lst.append(5) Lst.append(6.6) print(Lst)
Output
['ram', 5, 6.6]
You may ask is it necessary to create an empty list first and then add elements to it by appending elements to it. Is there any way that we can create a required list? Well, the answer is yes and this is how we can do it.
Lst = ["ram", 1, 5.5] print(Lst)
Output
['ram', 1, 5.5]
Here is another method to create a list
ele = (1, "ram", 5.5) Lst = list(ele) print(Lst)
Output
[1, 'ram', 5.5]
How to get each element?
lst = [1,5.5, "ram"] for i in range(len(lst)): print(lst[i])
Output
1 5.5 ram
Here, we have retrieved the elements in the list using the index of the list. Indexing of the list always starts from Zero. Also, len() is the built-in function that returns the length of the argument that is passed to it.
We can also retrieve the elements from the list without using an index. Here is how,
for element in lst: print(element)
Output
1 5.5 ram
Here, the word element represents the elements in list. This ‘element’ is just a variable name that points to each element in list.
Appending elements in list
lst = [1,5.5, "ram"] print("Original list: ", lst) lst.append("shyam") print("List after additon of element: ", lst)
Output
Original list: [1, 5.5, 'ram'] List after additon of element: [1, 5.5, 'ram', 'shyam']
Appending an element in list always adds an element at the last position. What if we want to add an element in between? To know let’s go further.
Inserting an element in list
Syntax:
list_variable_name.insert(index, element_to_insert)
Let’s continue with the previous example.
lst.insert(1, "hari") print(lst)
Output
[1, 'hari', 5.5, 'ram', 'shyam']
We can see that there is a new element ‘hari’ at position 1.
Removing last element in list
lst.pop() print(lst)
Output
[1, 'hari', 5.5, 'ram']
pop() removes the last element in list. We can use pop() to remove the other elements too.
Syntax:
pop(index)
Let’s take an example
lst.pop(1) print(lst)
Output
[1, 5.5, 'ram']
Value at index = 1, “hari” is removed.
Deleting elements from list
Syntax:
del list_variable_name[index]
Let’s continue with the previous example.
del lst[0] print(lst)
Output
[5.5, 'ram']
Clearing whole list
Syntax:
list_variable_name.clear()
lst.clear()
Output
[]
Python lists are mutable
It means that elements inside of a list can be changed. Let’s take an example
lst = ["ram", 6, 7.4] print("before change: ",lst) lst[0] = "shyam" print("after change: ",lst)
Output
before change: ['ram', 6, 7.4] after change: ['shyam', 6, 7.4]
Remove list element
Syntax:
list_variable_name.remove(element_to_remove)
lst = ["ram", 6, 7.4] lst.remove(6) print("list after removal: ", lst)
Output
list after removal: ['ram', 7.4]
Nested list
A nested list is a special kind of list that contains another list inside of it as an element.
lst = ["ram", [1,2,4.4], "five"] print(lst[0]) print(lst[1])
Output
ram [1, 2, 4.4]
Enumerate
Till now we have retrieved only elements from list. What if we have to retrieve their corresponding index also. For this we need enumerate().function. This function returns the index and element from list.
lst = ["ram", [1,2,4.4], "five"] for index, element in enumerate(lst): print(index, element)
Output
0 ram 1 [1, 2, 4.4] 2 five
Sorting a list
lst = [1,7,2,9,3,4] print("Before sorting: ", lst) lst.sort() print("After sorting: ", lst)
Output
Before sorting: [1, 7, 2, 9, 3, 4] After sorting: [1, 2, 3, 4, 7, 9]
We can see that the sorting is done in ascending order. To sort the list in descending order,
lst = [1,7,2,9,3,4] print("Before sorting: ", lst) lst.sort(reverse=True) print("After sorting: ", lst)
Output
Before sorting: [1, 7, 2, 9, 3, 4] After sorting: [9, 7, 4, 3, 2, 1]
How to slice a list?
Syntax:
list_variable_name[start: end : increment]
Let’s do some examples of it
lst = [1,5,3,8,"ram", 6.6, "shyam", 10] print(lst[0:5])
Output
[1, 5, 3, 8, 'ram']
Starting index is 0 and the end index is 5. But the output is up to index 4 because the end index is always exclusive.
lst = [1,5,3,8,"ram", 6.6, "shyam", 10] print(lst[5:])
Output
[6.6, 'shyam', 10]
starting index is 5 and the ending index is not mentioned. so, by default python prints all the elements after starting index 5. Here increment is not given and by default, it is taken as 1
lst = [1,5,3,8,"ram", 6.6, "shyam", 10] print(lst[5::-1])
Output
[6.6, 'ram', 8, 3, 5, 1]
Here, the index is -1 so it prints all the elements before starting index 5 because each time index is decremented. Using this we can reverse the list very easily.
lst = [1,5,3,8,"ram", 6.6, "shyam", 10] print(lst[::-1])
Output
[10, 'shyam', 6.6, 'ram', 8, 3, 5, 1]
Tuple
A tuple is another data structure in python. It encloses the elements in parenthesis. Tuples are immutable so they are more efficient than lists because during execution tuples do not get changed.
Creating an empty tuple
tup = tuple() print(type(tup))
Output
<class 'tuple'>
Accessing each element in tuple
for i in range(len(tup)): print(tup[i])
Output
1 4 ram 90.09
Here index is used to access the element in the tuple. We can access elements without using an index and here is how
for ele in tup: print(ele)
Output
1 4 ram 90.09
Python tuple are immutable
Tuple are immutable means that we cannot assign element to tuple after creating a tuple. Let’s try to assign element in previous example.
tup[0] = 78 print(tup)
Output
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-fcab05466a5f> in <module> ----> 1 tup[0] = 78 2 print(tup) TypeError: 'tuple' object does not support item assignment
Here, we got TypeError because the tuple does not support item assignment.
Some built-in functions in the tuple
Finding a maximum element in a tuple: max()
tup = (10, 45, 78.95, 33, 90) print("maximum element: ", max(tup))
Output
maximum element: 90
Finding a minimum element in tuple: min()
print("minimum element: ", min(tup))
Output
minimum element: 10
Finding the sum of all element: sum()
print("Total sum: ", sum(tup))
Output
Total sum: 256.95
Finding the index of a element: index()
find_index = 90 print("index of ", find_index, "is: ", tup.index(find_index))
Output
index of 90 is: 4
Dictionary
Dictionary is another data structure in python. It has key and value pair and is enclosed by curly braces.
Creating an empty dictionary
Dict = {} print(type(Dict))
Output
<class 'dict'>
Accessing elements in the dictionary
Dict = { "Name " : "Shiva", "Address ": "Rupandehi", "Age": 32, "Education ": "Bachelor in Engineering", "College ": "HCOE" } print(Dict)
Output
{'Name ': 'Shiva', 'Address ': 'Rupandehi', 'Age': 32, 'Education ': 'Bachelor in Engineering', 'College ': 'HCOE'}
Now let’s loop through the dictionary and access the elements
for key, value in Dict.items(): print(key, value)
Output
Name Shiva Address Rupandehi Age 32 Education Bachelor in Engineering College HCOE
We can use the get() method to access the value in a dictionary
print(Dict.get("Name ")) print(Dict.get("Address "))
Output
Shiva Rupandehi
Deleting data in the dictionary
Using del
del Dict["Name "] print(Dict)
Output
{'Address ': 'Rupandehi', 'Age': 32, 'Education ': 'Bachelor in Engineering', 'College ': 'HCOE'}
Using pop()
Dict.pop("College ") print(Dict)
Output
{'Address ': 'Rupandehi', 'Age': 32, 'Education ': 'Bachelor in Engineering'}
Set
Set is a collection of unique elements enclosed by curly braces.
Creating empty set
name = set() print(type(name))
Output
<class 'set'>
Accessing an element of the set
names = {"ram", "shyam", "gita", "sita"} for name in names: print(name)
Output
ram gita shyam sita
Uniqueness of set
names = {"ram", "shyam", "gita", "sita", "gita", "shyam"} print(names)
Output
{'ram', 'gita', 'shyam', 'sita'}
As there are some repeated elements assigned to names but while printing repeated elements in names got discarded and this is because sets always hold unique elements.
Union, Intersection, and difference
Let’s define two sets of names
name1 = {"ram", "shyam", "gita", "sita",} name12= {"mosh", "kane", "gyan", "sita", "gita", "shyam"}
Union
print("union is: ", name1.union(name2))
Output
union is: {'sita', 'shyam', 'gyan', 'kane', 'ram', 'mosh', 'gita'}
union of two sets results in the new set including all the unique elements from both and common elements too.
Intersection
print("intersection is: ", name1.intersection(name2))
Output
intersection is: {'gita', 'shyam', 'sita'}
The intersection of two sets results in the new set including only a common element in both sets.
Difference
print("name1 - name2 is: ", name1.difference(name2))
Output
name1 - name2 is: {'ram'}
Conclusion
A data structure in python holds the sequence of data. List, tuple, dictionary, and set are data structures in python. The list is mutable and not as efficient as the tuple while the tuple is immutable and doesn’t get altered during execution. Dictionary has key and value pair and is enclosed with curly braces and set always include unique element only.
Happy Learning 🙂