Data Structures in Python

Python Data Structures

In any programming language, we need to deal with data.  Now, one of the most fundamental things that we need to work with the data is to store, manage, and access it efficiently in an organized way so it can be utilized whenever required for our purposes. Data Structures are used to take care of all our needs.

What are Data Structures?

Data Structures are fundamental building blocks of a programming language. It aims to provide a systematic approach to fulfill all the requirements mentioned previously in the article. The data structures in Python are List, Tuple, Dictionary, and Set. They are regarded as implicit or built-in Data Structures in Python. We can use these data structures and apply numerous methods to them to manage, relate, manipulate and utilize our data.

We also have custom Data Structures that are user-defined namely Stack, Queue, Tree, Linked List, and Graph. They allow users to have full control over their functionality and use them for advanced programming purposes. However, we will be focussing on the built-in Data Structures for this article.

Implicit Data Structures Python
Implicit Data Structures Python

LIST

Lists help us to store our data sequentially with multiple data types. They are comparable to arrays with the exception that they can store different data types like strings and numbers at the same time. Every item or element in a list has an assigned index. Since Python uses 0-based indexing, the first element has an index of 0 and the counting goes on. The last element of a list starts with -1 which can be used to access the elements from the last to the first. To create a list we have to write the items inside the square brackets.

One of the most important things to remember about lists is that they are Mutable. This simply means that we can change an element in a list by accessing it directly as part of the assignment statement using the indexing operator.  We can also perform operations on our list to get desired output. Let’s go through the code to gain a better understanding of list and list operations.

1. Creating a List

#creating the list
my_list = ['p', 'r', 'o', 'b', 'e']
print(my_list)

Output

['p', 'r', 'o', 'b', 'e']

2. Accessing items from the List

#accessing the list 

#accessing the first item of the list
my_list[0]

Output

'p'
#accessing the third item of the list
my_list[2]
'o'

3. Adding new items to the list

#adding item to the list
my_list + ['k']

Output

['p', 'r', 'o', 'b', 'e', 'k']

4. Removing Items

#removing item from the list
#Method 1:

#Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# delete one item
del my_list[2]

print(my_list)

# delete multiple items
del my_list[1:5]

print(my_list)

Output

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Method 2:

#with remove fucntion
my_list = ['p','r','o','k','l','y','m']
my_list.remove('p')


print(my_list)

#Method 3:

#with pop function
print(my_list.pop(1))

# Output: ['r', 'k', 'l', 'y', 'm']
print(my_list)

Output

['r', 'o', 'k', 'l', 'y', 'm']
o
['r', 'k', 'l', 'y', 'm']

5. Sorting List

#sorting of list in ascending order

my_list.sort()
print(my_list)

Output

['k', 'l', 'm', 'r', 'y']
#sorting of list in descending order

my_list.sort(reverse=True)
print(my_list)

Output

['y', 'r', 'm', 'l', 'k']

6. Finding the length of a List

#finding the length of list

len(my_list)

Output

5

TUPLE

Tuples are very similar to lists with a key difference that a tuple is IMMUTABLE, unlike a list. Once we create a tuple or have a tuple, we are not allowed to change the elements inside it. However, if we have an element inside a tuple, which is a list itself, only then we can access or change within that list. To create a tuple, we have to write the items inside the parenthesis. Like the lists, we have similar methods which can be used with tuples. Let’s go through some code snippets to understand using tuples.

1. Creating a Tuple

#creating of tuple

my_tuple = ("apple", "banana", "guava")
print(my_tuple)

Output

('apple', 'banana', 'guava')

2. Accessing items from a Tuple

#accessing first element in tuple

my_tuple[1]

Output

'banana'

3. Length of a Tuple

#for finding the lenght of tuple

len(my_tuple)

Output

3

4. Converting a Tuple to List

#converting tuple into a list

my_tuple_list = list(my_tuple)
type(my_tuple_list)

Output

list

5. Reversing a Tuple

#Reversing a tuple

tuple(sorted(my_tuple, reverse=True)) 

Output

('guava', 'banana', 'apple')

6. Sorting a Tuple

#sorting tuple in ascending order

tuple(sorted(my_tuple)) 

Output

('apple', 'banana', 'guava')

7. Removing elements from Tuple

For removing elements from the tuple, we first converted the tuple into a list as we did in one of our methods above( Point No. 4) then followed the same process of the list, and explicitly removed an entire tuple, just using the del statement.

DICTIONARY

Dictionary is a collection which simply means that it is used to store a value with some key and extract the value given the key. We can think of it as a set of key: value pairs and every key in a dictionary is supposed to be unique so that we can access the corresponding values accordingly.

A dictionary is denoted by the use of curly braces { } containing the key: value pairs. Each of the pairs in a dictionary is comma separated. The elements in a dictionary are un-ordered the sequence does not matter while we are accessing or storing them.

They are MUTABLE which means that we can add, delete or update elements in a dictionary. Here are some code examples to get a better understanding of a dictionary in python.

An important point to note is that we can’t use a mutable object as a key in the dictionary. So, a list is not allowed as a key in the dictionary.

1. Creating a Dictionary

#creating a dictionary

my_dict = {
    1:'Delhi',
    2:'Patna',
    3:'Bangalore'
}
print(my_dict)
Output
{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}

Here, integers are the keys of the dictionary and the city name associated with integers are the values of the dictionary.

2. Accessing items from a Dictionary

#access an item

print(my_dict[1])

Output

'Delhi'

3. Length of a Dictionary

#length of the dictionary

len(my_dict)

Output

3

4. Sorting a Dictionary

#sorting based on the key 

Print(sorted(my_dict.items()))


#sorting based on the values of dictionary

print(sorted(my_dict.values()))

Output

[(1, 'Delhi'), (2, 'Bangalore'), (3, 'Patna')]

['Bangalore', 'Delhi', 'Patna']

5. Adding elements in Dictionary

#adding a new item in dictionary 

my_dict[4] = 'Lucknow'
print(my_dict)

Output

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore', 4: 'Lucknow'}

6. Removing elements from Dictionary

#for deleting an item from dict using the specific key

my_dict.pop(4)
print(my_dict)

#for deleting last item from the list

my_dict.popitem()

#for clearing the dictionary

my_dict.clear()
print(my_dict)

Output

{1: 'Delhi', 2: 'Patna', 3: 'Bangalore'}
(3, 'Bangalore')
{}

SET

Set is another data type in python which is an unordered collection with no duplicate elements. Common use cases for a set are to remove duplicate values and to perform membership testing. Curly braces or the set() function can be used to create sets. One thing to keep in mind is that while creating an empty set, we have to use set(), and not { }. The latter creates an empty dictionary.

Here are some code examples to get a better understanding of sets in python.

1. Creating a Set

#creating set

my_set = {"apple", "mango", "strawberry", "apple"}
print(my_set)

Output

{'apple', 'strawberry', 'mango'}

2. Accessing items from a Set

#to test for an element inside the set

"apple" in my_set

Output

True

3. Length of a Set

print(len(my_set))

Output

3

4. Sorting a Set

print(sorted(my_set))

Output

['apple', 'mango', 'strawberry']

5. Adding elements in Set

my_set.add("guava")
print(my_set)

Output

{'apple', 'guava', 'mango', 'strawberry'}

6. Removing elements from Set

my_set.remove("mango")
print(my_set)

Output

{'apple', 'guava', 'strawberry'}

Conclusion

In this article, we went through the most commonly used data structures in python and also saw various methods associated with them.

Further Readings

Reference

Please check out the official documentation for Python Data Structures containing exhaustive information about the same.