• Home
  • /
  • Blog
  • /
  • 10 Data Structures in Python That Kids Should Know

10 Data Structures in Python That Kids Should Know

Data Structures in Python

This post is also available in: हिन्दी (Hindi) العربية (Arabic)

Python has been used worldwide for different fields such as making websites, artificial intelligence, and much more. But to make all of this possible, data plays a very important role which means that this data should be stored efficiently and access to it must be timely. So how do you achieve this? We use something called Data Structures.

What is a Data Structure?

A data structure is a specialized format for organizing, processing, retrieving, and storing data. Various types of data structures are used in different programming languages, all designed to arrange data to suit a specific purpose. Data structures make it easy for users to access and work with the data they need in appropriate ways.

In computer science and computer programming, a data structure may be selected or designed to store data for the purpose of using it with various algorithms.

Types of Data Structures in Python

Python offers two types of data structures:

  • Built-In Data Structures
  • User-Defined Data Structures

Data Structures in Python
Data Structures in Python

Built-In Data Structures

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. 

Following are the built-in data structures in Python:

  • List
  • Dictionary
  • Tuple
  • Set

1. List

Lists are used to store data of different data types in sequential order. There are addresses assigned to every element of the list, which is called an index. The index value starts from 0 and goes on until the last element. Negative indexing is allowed which starts from -1 enabling you to access elements from the last to the first. 

Let’s understand the different operations in lists:

Creating a List

To create a list, you use the square brackets and add elements to it accordingly. If you do not pass any elements inside the square brackets, you get an empty list as the output.

my_list = [] #create empty list
print(my_list)
my_list = [1, 2, 3, 'example', 3.132] #creating list with data
print(my_list)

Output:

[]

[1, 2, 3, ‘example’, 3.132]

Inserting Element in a List

Elements can be inserted in a list by using 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 increases the size of the list too.

my_list = [1, 2, 3]
print(my_list)
my_list.append([555, 12]) #add as a single element
print(my_list)
my_list.extend([234, 'more_example']) #add as different elements
print(my_list)
my_list.insert(1, 'insert_example') #add element i
print(my_list)

Output:

[1, 2, 3]

[1, 2, 3, [555, 12]]

[1, 2, 3, [555, 12], 234, ‘more_example’]

[1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]

Deleting Element from a List

Elements can be deleted from a list by using keyword del, functions pop() and remove().

  • To delete elements, use the del keyword which is built into Python but this does not return anything back to us.
  • If you want the element back, you can use the pop() function which takes the index value.
  • To remove an element by its value, you can use the remove() function.

my_list = [1, 2, 3, 'example', 3.132, 10, 30]
del my_list[5] #delete element at index 5
print(my_list)
my_list.remove('example') #remove element with value
print(my_list)
a = my_list.pop(1) #pop element from list
print('Popped Element: ', a, ' List remaining: ', my_list)
my_list.clear() #empty the list
print(my_list)

Output:

[1, 2, 3, ‘example’, 3.132, 30]

[1, 2, 3, 3.132, 30]

Popped Element: 2 List remaining: 1, 3, 3.132, 30]

[]

Accessing Elements of a List

Accessing elements is the same as accessing Strings in Python. You can pass the index values and hence can obtain the values as needed.

my_list = [1, 2, 3, 'example', 3.132, 10, 30]
for element in my_list: #access elements one by one
    print(element)
print(my_list) #access all elements
print(my_list[3]) #access index 3 element
print(my_list[0:2]) #access elements from 0 to 1 and exclude 2
print(my_list[::-1]) #access elements in reverse

Output:

1

2

3

example

3.132

10

30

[1, 2, 3, ‘example’, 3.132, 10, 30]

example

[1. 2]

[30, 10, 3.132, ‘example’, 3, 2, 1]

Other Functions

  • The len() function returns to us the length of the list.
  • The index() function finds the index value of the 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 both sort the values of the list. The sorted() has a return type whereas the sort() modifies the original list.

my_list = [1, 2, 3, 10, 30, 10]
print(len(my_list)) #find length of list
print(my_list.index(10)) #find index of element that occurs first
print(my_list.count(10)) #find count of the element
print(sorted(my_list)) #print sorted list but not change original
my_list.sort(reverse=True) #sort original list
print(my_list)

Output:

6

3

2

[1, 2, 3, 10, 10, 30]

[30, 10, 10, 3, 2, 1]

2. Dictionary

Dictionaries are used to store key-value pairs. Dictionary can be thought of as a phone directory containing hundreds and thousands of names and their corresponding numbers. Here the constant values Name and the Phone Numbers are called the keys. The various names and phone numbers are the values that have been fed to the keys. If you access the values of the keys, you will obtain all the names and phone numbers. So that is what a key-value pair is. In Python, this structure is stored using Dictionaries.

Creating  a Dictionary

Dictionaries can be created using the braces or using the dict() function. You need to add the key-value pairs whenever you work with dictionaries.

my_dict = {} #empty dictionary
print(my_dict)
my_dict = {1: 'Python', 2: 'Java'} #dictionary with elements
print(my_dict)

Output:

{}

{1: ‘Python’, 2: ‘Java’}

Changing and Adding key, value pairs

To change the values of the dictionary, you need to do that using the keys. So, you first access the key and then change the value accordingly. To add values, you simply add another key-value pair as shown below:

my_dict = {'First': 'Python', 'Second': 'Java'}
print(my_dict)
my_dict['Second'] = 'C++' #changing element
print(my_dict)
my_dict['Third'] = 'Ruby' #adding key-value pair
print(my_dict)

Output:

{‘First’: ‘Python’, ‘Second’: ‘Java’}

{‘First’: ‘Python’, ‘Second’: ‘C++’}

{‘First’: ‘Python’, ‘Second’: ‘C++’, ‘Third’: ‘Ruby’}

Deleting key, value pairs

Elements can be deleted from a dictionary by using functions pop(), popitem() and clear().

  • To delete the values, you use the pop() function which returns the value that has been deleted.
  • To retrieve the key-value pair, you use the popitem() function, which returns a key and value tuple.
  • To clear the entire dictionary, you use the clear() function.

my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}
a = my_dict.pop('Third') #pop element
print('Value:', a)
print('Dictionary:', my_dict)
b = my_dict.popitem() #pop the key-value pair
print('Key, value pair:', b)
print('Dictionary', my_dict)
my_dict.clear() #empty dictionary
print('n', my_dict)

Output:

Value: Ruby

Dictionary: {‘First’: ‘Python’, ‘Second’: ‘Java’}

Key, value pair: (‘Second’, ‘Java’)

Dictionary {‘First’: ‘Python’}

{}

Accessing Elements

You can access elements using the keys only. You can use either the get() function or just pass the key values and you will be able to retrieve the values.

my_dict = {'First': 'Python', 'Second': 'Java'}
print(my_dict['First']) #access elements using keys
print(my_dict.get('Second'))

Output:

Python

Java

Other Functions

Apart from these basic operations, there are few other functions to perform specific tasks. These are:

  • keys(): It returns the key.
  • values(): It is used to return the value.
  • items(): It returns the key-value pair.

my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}
print(my_dict.keys()) #get keys
print(my_dict.values()) #get values
print(my_dict.items()) #get key-value pairs
print(my_dict.get('First'))

Output:

dict_keys([‘First’, ‘Second’, ‘Third’])

dict_values([‘Python’, ‘Java’, ‘Ruby’])

dict_items([(‘First’, ‘Python’), (‘Second’, ‘Java’), (‘Third’, ‘Ruby’)])

Python

3. Tuple

Tuples are similar to lists except that the data once entered into the tuple cannot be changed under any circumstances. The only exception is when the data inside the tuple is mutable. The following example will help you understand.

Creating a Tuple

You can create a tuple using parenthesis or using the tuple() function.

my_tuple = (1, 2, 3) #create tuple
t2 = tuple([1, 4, 6])
print(my_tuple)
print(t2)

Output:

(1, 2, 3)

(1, 4, 6)

Accessing Elements

Accessing elements is the same as it is for accessing values in lists.

my_tuple2 = (1, 2, 3, 'phyton') #access elements
for x in my_tuple2:
    print(x)
print(my_tuple2)
print(my_tuple2[0])
print(my_tuple2[:])
print(my_tuple2[3][4])

Output:

1

2

3

python

(1, 2, 3, ‘python’)

1

(1, 2, 3, ‘python’)

o

Appending Elements

To append the values, you use the ‘+’ operator which will take another tuple to be appended to it.

my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6) #add elements
print(my_tuple)

Output:

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

Other Functions

Apart from these basic operations, there are few other functions to perform specific tasks. The following example explains these functions.

my_tuple = (1, 2, 3, ['hindi', 'python'])
my_tuple[3][0] = 'english'
print(my_tuple)
print(my_tuple.count(2))
print(my_tuple.index(['english', 'python']))

Output:

(1, 2, 3, [‘english’], [‘python’])

1

3

4. Set

Sets are a collection of unordered elements that are unique. It means that even if the data is repeated more than once, it would be entered into the set only once. It resembles the sets that you have learned in Mathematics. The operations also are the same as is with those in Mathematics.

Creating a Set

Sets are created using the curly braces but instead of adding key-value pairs, you just pass values to it.

my_set = {1, 2, 3, 4, 5, 5, 5} #create set
print(my_set)

Output:

{1, 2, 3, 4, 5}

Adding Elements

To add elements, you use the function add() and pass the value to it.

my_set = {1, 2, 3}
my_set.add(4) #add element to set
print(my_set)

Output:

{1, 2, 3, 4}

Operations in Sets

  • The union() function combines the data present in both sets.
  • The intersection() function finds the common data present in both sets.
  • The difference() function deletes the data present in both and outputs data present only in the set passed.
  • The symmetric_difference() does the same as the difference() function but outputs the data which is remaining in both sets.

The following example explains the operations in a set.

my_set = {1, 2, 3, 4}
my_set_2 = {3, 4, 5, 6}
print(my_set.union(my_set_2), '----------', my_set | my_set_2)
print(my_set.intersection(my_set_2), '----------', my_set & my_set_2)
print(my_set.difference(my_set_2), '----------', my_set - my_set_2)
print(my_set.symmetric_difference(my_set_2), '----------', my_set ^ my_set_2)
my_set.clear()
print(my_set)

Output:

{1, 2, 3, 4, 5, 6} —————– {1, 2, 3, 4, 5, 6}

{3, 4} ————— {3, 4}

{1, 2} ————— {1, 2}

{1, 2, 5, 6} ————— {1, 2, 5, 6}

set()

User-Defined Data Structures

These are the data structures that aren’t supported by Python but can be programmed to reflect the same functionality using concepts supported by Python.

1. Stack

Stacks are linear data structures based on the principle of Last-In-First-Out (LIFO) where data entered last will be the first to get accessed. It is built using the array structure and has two operations viz. Push (adding element) elements and pop (deleting element) and accessing elements from one of the two ends in the stack call as the TOP. This TOP is the pointer to the current position of the stack. Stacks are prominently used in applications such as Recursive Programming, reversing words, undo mechanisms in word editors, and so forth.

stack = ['first', 'second', 'third']
print(stack)
print()
# pushing elements
stack.append('fourth')
stack.append('fifth')
print(stack)
print()
# printing top
n = len(stack)
print(stack[n-1])
print()
# poping element
stack.pop()
print(stack)

Output:

[‘first’, ‘second’, ‘third’]

[‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’]

fifth

[‘first’, ‘second’, ‘third’, ‘fourth’]

2. Queue

A queue is a linear data structure that allows the insertion of elements from one end (called REAR) and deletion from the other (called FRONT). Thus it follows the First In First Out (FIFO) methodology.

queue = ['first', 'second', 'third']
print(queue)
print()
# pushing elements
queue.append('fourth')
queue.append('fifth')
print(queue)
print()
# printing head
print(queue[0])
# printing tail
n = len(queue)
print(queue[n-1])
print()
# poping element
queue.remove(queue[0])
print(queue)

Output

[‘first’, ‘second’, ‘third’]

[‘first’, ‘second’, ‘third’, ‘fourth’, ‘fifth’]

first

fifth

[‘second’, ‘third’, ‘fourth’, ‘fifth’]

3. Tree

A tree is a non-linear but hierarchical data structure. The topmost element is known as the root of the tree since it is believed to start from the root. The elements at the end of the tree are known as its leaves (singular leaf). Trees are appropriate for storing data that aren’t linearly connected to each other but form a hierarchy.

class node:
	def __init__(self, ele):
		self.ele = ele
		self.left = None
		self.right = None
def preorder(self):
	if self:
		print(self.ele)
		preorder(self.left)
		preorder(self.right)
n = node('first')
n.left = node('second')
n.right = node('third')
preorder(n)

You can see the Tree traversals here.

Output:

first

second

third

4. Linked List

A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the image below:

llist = ['first', 'second', 'third']
print(llist)
print()
# adding elements
llist.append('fourth')
llist.append('fifth')
llist.insert(3, 'sixth')
print(llist)
print()
llist.remove('second')
print(llist)
print()

Output:

[‘first’, ‘second’, ‘third’]

[‘first’, ‘second’, ‘third’, ‘sixth’, ‘fourth’, ‘fifth’]

[‘first’, ‘third’, ‘sixth’, ‘fourth’, ‘fifth’]

5. Graph

A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. A graph consists of a finite set of vertices (or nodes) and edges that connect a pair of nodes.

class adjnode:
	def __init__(self, val):
		self.val = val
		self.next = None
class graph:
	def __init__(self, vertices):
		self.v = vertices
		self.ele = [None]*self.v
	def edge(self, src, dest):
		node = adjnode(dest)
		node.next = self.ele[src]
		self.ele[src] = node
	node = adjnode(src)
		node.next = self.ele[dest]
		self.ele[dest] = node
	def __repr__(self):
		for i in range(self.v):
			print("Adjacency list of vertex {}\n head".format(i), end="")
			temp = self.ele[i]
			while temp:
				print(" -> {}".format(temp.val), end="")
				temp = temp.next
g = graph(4)
g.edge(0, 2)
g.edge(1, 3)
g.edge(3, 2)
g.edge(0, 3)
g.__repr__()

Output:

Adjacency list of vertex 0

head -> 3 -> 2

Adjacency list of vertex 1

head -> 3

Adjacency list of vertex 2

head -> 3 -> 0

Adjacency list of vertex 3

head -> 0 -> 2 -> 1

6. Hash Map

Hashmaps are indexed data structures. A hashmap makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index. The key is unique and immutable. In Python, dictionaries are examples of hashmaps.

def printdict(d):
	for key in d:
		print(key, "->", d[key])
hm = {0: 'first', 1: 'second', 2: 'third'}
printdict(hm)
print()
hm[3] = 'fourth'
printdict(hm)
print()
hm.popitem()
printdict(hm)

Output:

0 -> first

1 -> second

2 -> third

0 -> first

1 -> second

2 -> third

3 -> fourth

0 -> first

1 -> second

2 -> third

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>