Python Data Structures

Python provides several built-in data structures to help us efficiently handle large amounts of data.

Python provides four primary built-in data structures:

  • List
  • Tuple
  • Dictionary
  • Set

Let’s study each one of them in brief.

This tutorial is a part of the free course – learn python from scratch. Enroll to this free course to learn Python from scratch.

List

The list is the most commonly used data structure in Python. It allows us to store elements of different data types in one container.

The contents of a list are enclosed by square brackets, [ ].

Let’s learn by example code.

lists = ["Codeforgeek", "Courses", "Lessons", 130]
print(lists)

# Indexing
print(lists[0])

# Length
print(len(lists))

The values in the list are mutable hence we can change them on the fly.

lists = ["Codeforgeek", "Courses", "Lessons", 130]
print(lists)

# Change the value
lists[3] += 5
print(lists)

This should output the following:

['Codeforgeek', 'Courses', 'Lessons', 130]
['Codeforgeek', 'Courses', 'Lessons', 135]

We can use the list() method to cast the existing range() values in a list.

Here is a simple example.

num_seq = range(0, 10)
num_list = list(num_seq)
print(num_list)

We can also create a nested list i.e lists inside a list.

num = [[1,2],[3,4],[5,6,7,8,9,10],[0.5]]
print(num[0][1]) #prints 2

We can create a 3×3, 4×4, 3×4 lists. Very useful in computer graphics and mathematical problems.

To add a new element in the existing list, we can use the append() and insert() method.

num_list = [1,2]
num_list.append(3) # add 3 at the end of the list
print(num_list)
num_list.insert(3, 40)  # Inserting 40 at the 3rd index and shifts the index of the list
print(num_list)

The output of the code:

[1, 2, 3]
[1, 2, 3, 40]

Similarly, we can remove the element from the list using pop() or remove() functions.

num_list = [1,2,3,4,5]
num_list.pop()
print(num_list)
num_list.remove(3)  # removes 3 from the list
print(num_list)

The output of the code:

[1, 2, 3, 4]
[1, 2, 4]

We can sort the list in the ascending order using sort() method.

num_list = [20, 40, 10, 50.4, 30, 100, 5]
num_list.sort()
print(num_list)

The output of the code:

[5, 10, 20, 30, 40, 50.4, 100]

Let’s study the next data structure i.e tuples.

Tuple

A tuple is a list that is immutable i.e once it is declared, the value cannot be changed. However, a tuple can contain a list, and values in the list can be changed.

Let’s learn by example.

num_lists = (1,2,3,4,5,6,7,8,9,10)
print(num_lists)
print(num_lists[0])
print(len(num_lists))

If you observe we initialized the tuple using ( ) instead of [ ] as we do on the list.

Since tuples are immutable, we can’t change the value inside the tuple. However, we can use nested tuple and use lists inside the tuple to change the values if required.

Let’s learn by example.

num_lists=([1,2,3],[4,5,6])
print(num_lists[0])
# change value of list inside the tuple
num_lists[0][0] += 5
print(num_lists)

The output of the code.

[1, 2, 3]
([6, 2, 3], [4, 5, 6])

You can search in the tuples.

cities = ("London", "Paris", "Los Angeles", "Tokyo")
print("London" in cities) # True
print("Mumbai" in cities) # False

Let’s learn the next data structure i.e Dictionaries.

Dictionary

A dictionary stores data in key-value pairs, where each unique key is an index that holds the value associated with it. If you are familiar with JSON data type in JavaScript then dictionary data type is similar to that.

Dictionary data type is initialized using key:value format inside curly brackets { }.

Let’s learn by example.

userId = {
    "100": "Shahid",
    "120": "John",
    "130": "Mary"
}

print(userId)
print(len(userId))
print(userId["100"])

The output of the code:

{'100': 'Shahid', '130': 'Mary', '120': 'John'}
3
Shahid

Observe the third print() statement. Using the key, we can retrieve the data from the dictionary.

It’s so useful in building a large set of applications.

You can also access the values using get() method. Pass the key in the get() method to retrieve values.

To add/update the new/existing element in the existing dictionary, we can use the following code.

userId = {
    "100": "Shahid",
    "120": "John",
    "130": "Mary"
}

userId["150"] = "Wick" # add new entry
userId["100"] = "Shahid Shaikh"
print(userId)

The output of the code above.

{'100': 'Shahid Shaikh', '130': 'Mary', '120': 'John', '150': 'Wick'}

To remove the values from the dictionary, we can use the pop() or popitem() method.

userId = {
    "100": "Shahid",
    "120": "John",
    "130": "Mary"
}

removedItem = userId.pop("100")
lastItem = userId.popitem()
print(removedItem)
print(lastItem)

We can check whether the key exists or not using the in operator.

userId = {
    "100": "Shahid",
    "120": "John",
    "130": "Mary"
}

print("100" in userId) # True
print("500" in userId) # False

Let’s learn our last data structure i.e sets.

Set

A Set is a simple data structure that contains non-duplicate unordered items. Sets do not allow duplicate values and there is no way to fetch the values from a Set without iterating through it.

Let’s learn by example.

test_set = {1,2,3,"Shahid", (1.5,2.5)}
print(test_set)
print(len(test_set))  # Length of the set

A Set also holds values inside the curly brackets similar to dictionaries except there is no key:value pair.

To add a new element or elements in the Set, we can use add() or update() methods.

new_set = {1,2,3}
new_set.add(10)
print(new_set)

new_set.update([20, 30, 40])
print(new_set)

Similarly, we can remove elements from Set as well. We can use the remove() method.

new_set = {1,2,3,4,5}
print(new_set)

new_set.remove(5)
print(new_set)

We can iterate through the Set as well.

new_set = {1,2,3,4,5}

for set_value in new_set:
    print(set_value)

I highly recommend you to deep dive more in the data structures in Python. It’s important and crucial for interviews in FAANG companies as well as it is going to help you become a better software developer.

This tutorial is a part of the free course – learn python from scratch. Enroll to this free course to learn Python from scratch.

Pankaj Kumar
Pankaj Kumar
Articles: 207