In recent years, Python has become the most popular language for those new to programming due to its ease of use and its growing popularity in the Artificial Intelligence and Data Science Jobs market.

Due to this growing popularity, I decided to list down and explaining the most important data structures in python that every python beginner must understand.

If you enjoy this article, do check out my other articles here.

I have covered the following data structures;

  • lists
  • tuples
  • dictionary
  • set

List

Python list is a collection of items. A python list can contain multiple data types and the most important thing to keep in mind is that they are mutable objects.

The word ‘Mutable’ means that they can be altered after creation i.e. you can easily add or remove elements from this collection. Let’s see some examples of how lists are formed and manipulated.

Lists are identified by square brackets ‘[]’.

#initializing a list
lst = []

print("Type of this variable is:", type(lst))

#adding items to the list
lst.append(1)
lst.append("String item")
lst.append(1.6)

print("Your list contains:",lst)

The above list methods show we can initialize a list and then add items to it. The list append function is a built-in method for the list class which allows us to add elements to the list.

Output of list creation
The output of list creation

Now let’s try removing some elements.

#remove some items from the list
lst.remove("String item")
lst.remove(1)

print("The list now contains:", lst)

The remove() function is of the list class and is used for removing elements from a list.

Output from removing elements.
Output from removing elements.

There are multiple methods of removing elements from a list. Another useful method is the pop() method. Using pop() not only removes the element from the list but returns it back to the user.

#initializing a list with some elements already in it
new_lst = [1,2,4.5,"element"]

#pop out the element at index 2
ele = new_lst.pop(2)

print("Retrieved Element:", ele)
print("List after removal of element", new_lst)
Output after performing pop()
Output after performing pop()

A major difference you must have noticed between pop() and remove() is that the latter removes the element from the list and nothing more, the former returns the element to you which you can store in a variable. Both of these have their uses depending on your problem.


Tuples

Python tuples are also a collection of elements and a quick glance would make you think that tuples are very similar to lists however, there are certain major points that set these two miles apart.

What are tuples in python ?

In python, tuples are identified by round brackets ‘ () ’ and unlike lists, tuples are immutable. This means that they are allocated a certain memory location and size at the time of creation and after that, they cannot be manipulated i.e. you can not add or remove elements from a tuple.

Let’s see some examples;

#creating an empty tuple
x = ()
print("x is a:", type(x))
tuple
x belongs to the tuple class

Let’s try adding some elements;

#place a number at the 0th index
x[0] = 24
error message
error on assignment

Whoops!! what happened there? Well, this is what I meant when I said tuples are immutable. So how do we add elements to it?

Well technically you don’t ‘add’ elements to it, you have to define its elements when creating it. There are a number of ways to do so.

#creating a tuple
x = (1,2,"Third Element")
print("Current tuple:", x)

#creating tuple using the tuple class constructor
y = tuple([1,5,5.5])
print("Tuple y:, y)
Filled Tuples
Filled tuples

Notice how I have passed to the tuple constructor in the second example above. The tuple constructor can convert any collection of items to a tuple.

Tuples are indexable though. You can pick out items from a tuple based on their index.

#accessing first element of x
print("The first element of x is:",x[0])

#accessing last element of y
print("The last element of y is:",y[-1])
Tuple Indexing
Tuple Indexing

Bonus Tip: Indexing elements from the end of a collection can be done by using negative numbers i.e. -1 refers to the very last element and -2 refers to the second to last and so on.

Dictionary

The Python dictionary comprehension holds elements in the form of key-value pairs. They are identified by curly braces ‘ {} ’ in python and like lists, these are also mutable objects.

In a dictionary, each element (value) is identified by its key. The general structure of a dictionary is shown below.

dictionary structure illustration
Dictionary Structure

The key and value pairs have a one-to-one mapping.

#initialising a dictionary
dictionary = {}

#Setting key-value pairs
dictionary[1] = "First Element"
dictionary["Second"] = "Second Element"
dictionary[3] = ["This", "is", "a", "list"]

print("Our Dictionary: n", dictionary)
Our dictionary

The above dictionary example aims at explaining the following key points:

  • How to add to dictionary python.
  • One key can point to one value (That value can be an array as well).
  • The keys of a dictionary can be of multiple data types (int, string, etc.) but it must be a single element (and not an array).
  • Values can also have multiple data types AND can also be a collection of elements such as a list or a tuple.
  • Key-Value pairs are separated by a comma in a single dictionary.

Let’s see how we can traverse a dictionary.

#print all keys and values using a loop
for key, value in dictionary.items():
    print(key, "points to (", value, ")")
    
print("n")

#printing all the keys from the dictionary
print(dictionary.keys())
print("n")

#printing all the values from the dictionary
print(dictionary.values())

print("n")

#printing values according to a given key
print("Values pointed to by given keys")
print("3 points to:",dictionary[3])
print("'Second' points to:",dictionary["Second"])
Outputs from above code
Outputs from the above code

That is the dictionary structure summed up.


Set

Sets are very different from the structures we have talked about above. These are mutable objects (can be changed after creation) but they also have a unique property that they only allow unique elements to be stored in them. Set elements are also non-indexable (this will become clearer in the examples ahead).

Similar to dictionaries, Sets are also identified by curly braces ( {} ) however they cannot be initialized by simply typing ‘{}’ since python will recognize that as a dictionary. Sets are initialized by using the set class constructor.

#initilize the set
a = set()

#add elements to the set
a.add(1)
a.add(3)
a.add(4)

#view elements of the set
print(a)
set
The set we just created

Let’s see if we can add a duplicate item into them;

#trying to add 3 again
a.add(3)

print(a)
no duplicate item was added

As expected, duplicate 3 was not added to our set. Let’s try with another example.

#creating a list with duplicate items
lst = [1,1,1,1,2,2,3,4,5,7,2,56, "element", "element"]

#converting the list to set
lst_set = set(lst)

print('Our original list:', lst)
print('Converted to a set:',lst_set)
Duplicate elements removed from the list when converted to a set
Duplicate elements removed from the list when converted to a set

We can also perform other functions on sets such as intersection and union. A python set union is similar to what we do in mathematics; it combines unique elements from both sets and the python set intersection would keep only elements common to both sets.

The End

That pretty much summarizes the main data structures in python that every beginner must know. In your journey as a python developer or a data scientist, a strong grasp of these data structures will surely give you an edge.

Leave a Reply

Your email address will not be published. Required fields are marked *