 # The Beginner’s Guide to Python Data Structures

### Introduction

As the name implies data structure are structures that holds some related data. Python has built-in data structure such as list, tuple, dictionary and set. These all data structures are used to store the data.

### List

List is one of the built-in data structure available in python. List holds the sequence of data enclosed by square bracket and separated by 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.

To add elements in an empty list we can use 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 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 elements?

``````lst = [1,5.5, "ram"]
for i in range(len(lst)):
print(lst[i])``````

Output

``````1
5.5
ram``````

Here, we have retrieve the elements in list using index of list. Indexing of list always starts from Zero. Also len() is the built-in function that returns the length of argument that is passed to it.

We can also retrieve the elements from list without using 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 which 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 add element at last position. What if we want to add a 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 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 element from list

##### Syntax:
``del list_variable_name[index]``

#### Let’s continue with previous example.

``````del lst
print(lst)``````

Output

``[5.5, 'ram']``

#### Clearing whole list

##### Syntax:
``list_variable_name.clear()``
``lst.clear()``

Output

``[]``

#### Python list are mutable

It means that element inside of a list can be changed. Let’s take an example

``````lst = ["ram", 6, 7.4]
print("before change: ",lst)
lst = "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

Nested list is a special kind of list that contains another list inside of it as element.

``````lst = ["ram", [1,2,4.4], "five"]
print(lst)
print(lst)``````

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 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 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 example on 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 end index is 5. But output is upto index 4, because 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 ending index is not mentioned. so, by default python prints all the element after start 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, index is -1 so it prints all the elements before start index 5 because the each time index is decremented. Using this we can reverse 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

Tuple is another data structure in python. It encloses the elements in parenthesis. Tuple are immutable so they are efficient than list because during excution tuple 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 tuple. We can access element without using 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 = 78
print(tup)``````

Output

``````---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-fcab05466a5f> in <module>
----> 1 tup = 78
2 print(tup)

TypeError: 'tuple' object does not support item assignment``````

`Here, we got TypeError because tuple does not support item assignment.`

#### Finding maximum element in tuple: max()

``````tup = (10, 45, 78.95, 33, 90)
print("maximum element: ", max(tup))``````

Output

``maximum element:  90``

#### Finding minimum element in tuple: min()

``print("minimum element: ", min(tup))``

Output

``minimum element:  10``

#### Finding sum of all element: sum()

``print("Total sum: ", sum(tup))``

Output

``Total sum:  256.95``

#### Finding 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 enclosed by curly braces.

#### Creating an empty dictionary

``````Dict = {}
print(type(Dict))``````

Output

``<class 'dict'>``

#### Accessing element in dictionary

``````Dict = {
"Name " : "Shiva",
"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 dictionary and access the elements

``````for key, value in Dict.items():
print(key, value)``````

Output

``````Name  Shiva
Age 32
Education  Bachelor in Engineering
College  HCOE``````

`We can use get() method to access the value in dictionary`

``````print(Dict.get("Name "))

Output

``````Shiva
Rupandehi``````

#### Deleting data in 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 collection of unique element enclosed by curly braces.

#### Creating empty set

``````name = set()
print(type(name))``````

Output

``<class 'set'>``

#### Accessing element of 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 of the repeated element assigned to names but while printing repeated element in names got discarded and this is because set always hold unique element.

#### Union, Intersection and difference

Let’s define two set 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 set result in new set including all the unique element from both and common element too.

#### Intersection

``print("intersection is: ", name1.intersection(name2))``

Output

``intersection is:  {'gita', 'shyam', 'sita'}``

Intersection of two set result in new set including only common element in both set.

#### Difference

``print("name1 - name2 is: ", name1.difference(name2))``

Output

``name1 - name2 is:  {'ram'}``

### Conclusion

Data structure in python holds the sequence of data. List, tuple, dictionary and set are data structure in python. List are mutable and not as efficient as tuple while tuple is immutable and don’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 🙂