Organizing, managing and storing data is important as it enables easier access and efficient modifications. Data Structures allows you to organize your data in such a way that enables you to store collections of data, relate them and perform operations on them accordingly.
Types of Data Structures in Python
Python has implicit support for Data Structures which enable you to store and access data. These structures are called List, Dictionary, Tuple and Set.
Python allows its users to create their own Data Structures enabling them to have full control over their functionality. The most prominent Data Structures are Stack, Queue, Tree, Linked List and so on which are also available to you in other programming languages. So now that you know what are the types available to you, why don’t we move ahead to the Data Structures and implement them using Python.
As the name suggests, these Data Structures are built-in with Python which makes programming easier and helps programmers use them to obtain solutions faster. Let’s discuss each of them in detail.
Lists are used to store data of different data types in a sequential manner. There are addresses assigned to every element of the list, which is called as Index. The index value starts from 0 and goes on until the last element called the positive index. There is also negative indexing which starts from -1 enabling you to access elements from the last to first. Let us now understand lists better with the help of an example program.
To create a list, you use the square brackets and add elements into it accordingly. If you do not pass any elements inside the square brackets, you get an empty list as the output.
Adding Elements
Adding the elements in the list can be achieved using the append(), extend() and insert() functions.
The append() function adds all the elements passed to it as a single element.
The extend() function adds the elements one-by-one into the list.
The insert() function adds the element passed to the index value and increase the size of the list too.
Deleting Elements
To delete elements, use the del keyword which is built-in into Python but this does not return anything back to us.
If you want the element back, you use the pop() function which takes the index value.
To remove an element by its value, you use the remove() function.
Accessing Elements
Accessing elements is the same as accessing Strings in Python. You pass the index values and hence can obtain the values as needed.
Other Functions
You have several other functions that can be used when working with lists.
The len() function returns to us the length of the list.
The index() function finds the index value of value passed where it has been encountered the first time.
The count() function finds the count of the value passed to it.
The sorted() and sort() functions do the same thing, that is to sort the values of the list. The sorted() has a return type whereas the sort() modifies the original list.