Python — Introduction to Data Structures

Data structures are a very important aspect of any language. Through data structures, we can solve many complex problems. We can also execute our programs faster with minimum time and space complexity.

Python has 4 basic types of in-built data structures.

  1. List
  2. Dictionary
  3. Tuple
  4. Set

List & Tuple:

List and tuples are an ordered sequence of values indexed by integer numbers. Moreover, the list and tuples are similar to each other there is only one difference between them. Lists are mutable and tuples are immutable (you can’t manipulate any elements in the tuple once created).

Creating a list/tuple:

list = []
tuple = ()

Length of tuple/list:

l=[12,13,14,15]/l=(12,13,14,15)
len(l)
4

Index of element ‘X’ of list/tuple:

l=[12,13,14,15]/l=(12,13,14,15)
l.i­nd­ex(­13)
1
If not found, throws a Value­Error exception

Count of occurrences of X in list/tuple:

l=[12,12,12,13,14,15]/l=(12,12,12,13,14,15)
l.count(12)
3

Update an item of List/tuple:

Lists:
l=['a','b','c','d']
l[3] = 'x'
print(l)
['a','b','c','x']Tuples: tuples are immutable!

Remove element in position X of list/tuple:

Lists:
l=['a','b','c','d']
del l[1] #removing the element in mentioned index
l.pop() #removing the last element
print(l)
['a','c']Tuples: tuples are immutable!

Concatenate two lists/tuples:

Lists: myList1 + myList2
Tuples: myTuple1 + myTuple2
Concatenating a List and a Tuple will produce a TypeE­rror exception

Insert element in position x of a list/t­uple:

Lists: myLis­t.i­nse­rt(x, "value")
Tuples: tuples are immutable!

Append “­x” to a list/t­uple:

Syntax: Lists: myList.append("x")
Tuples: tuples are immutable!

Convert a list/tuple to tuple/list:

Syntax: List to Tuple: tuple(myList)
Tuple to List: list(­myT­uple)

Some extra In-built functions:

min(a): Gives minimum value in amax(a): Gives minimum value in asum(a): Adds up items of an iterable and returns sumsorted(a): Sorted list copy of a

Dictionaries:

It is an unordered set of key-value pairs. In python you can only access the keys of the dictionaries, one of the main features of the dictionary is its a fast and efficient way to store data.

Initialize an empty Dictionary:

d = {}

Add an element with key “­name” to the Dictionary:

d["name­"] = 'jon'{'name':'jon'}

Update the element with key “name”:

Syntax:

d["name"] = 'tom'
d['age'] = 25
{'name':'tom','age':25}

Get element with key “­k”:

d["name­"]'tom' -- If the key is not present, a KeyError is raised

Check if the dictionary has key “­k”:

"name" in dTrue

Get the list of keys:

d.k­eys()['name','age']

Get the size of the Dictionary:

len(d)2

Delete element with key “­k” from the Dictionary:

del d­["name"]{'age':25}

Delete all the elements in the Dictionary:

d.c­lear(){}

Sets:

A set is a sequence of objects which is unordered and unindexed. Their values are also unchangeable which we will discuss later on.

Creating Sets:

Sets are denoted by curly brackets in Python. To create a set, you just have to write comma-separated values and store them in a variable.

mySet = {“Pakistan”, “Berlin”, “Iran”, “China”, “Palestine”}
print(mySet)

When the above code is executed, it produces the following result:

{'Pakistan', 'Berlin', 'Iran', 'China', 'Palestine'}

Note: Whenever you print sets, the order of the elements will differ as they are unordered.

Accessing Elements in Sets:

You cannot access elements of a set by using indices as the elements of a set are unordered and don’t have indices attached to them. However, you can use a set in a for loop to use its values.

for i in mySet:
print(i)

When the above code is executed, it produces the following result:

‘Pakistan’
‘Berlin’
‘Iran’
‘China’
‘Palestine’

You can also use the in keyword to check if a value is present in a set.

print(“America” in mySet)False

Modifying Sets:

The elements of a set are immutable while you can add more values to a set. To add a value to a set, the add method is used.

mySet.add(“Moscow”)
print(mySet)

When the above code is executed, it produces the following result:

{'Pakistan', 'Iran', 'Berlin', ‘Moscow’,'Palestine', 'China'}

To add multiple values or another set to a set add the set time, use the update method.

mySet.update({“America”, “Australia”, “Africa”}) #you can also    
provide a list here
print(mySet)

When the above code is executed, it produces the following result:

{‘Moscow’, 'Pakistan', ‘America’, ‘Berlin’, 'Iran', ‘Australia’, 'China', 'Palestine', ‘Africa’}

Deleting Sets and Set Elements:

Deleting sets is simple like all other sequences, just use the del keyword with the name of the set and it will be deleted.

del mySet

However, to delete the elements of a set, you can use the method remove.

mySet.remove(“Moscow”)
print(mySet)

When the above code is executed, it produces the following result:

{'Pakistan', ‘America’, ‘Berlin’, 'Iran', ‘Australia’, 'China', 'Palestine', ‘Africa’}

Remove raises an error if the element is not present in the set. If you are not sure if an item is in a list or not, you can use discard. It will delete it if it is there and raise no error if the value is not found.

mySet.discard(“America”)
print(mySet)

When the above code is executed, it produces the following result:

{'Pakistan', ‘Berlin’, 'Iran', ‘Australia’, 'China', 'Palestine', ‘Africa’}

And that’s it! Hope you found this to be a useful introduction to Python data structures.

Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store