Python built-in data structures help developers and data scientists store, organize, and manage efficient data access and tampering. There are various built-in data structures that will aid in algorithms, which include the following:
List
Tuple
Set
Dictionaries
There are other data structures that are user-defined, namely: graphs, trees, linked lists, and searching and sorting algorithms.
The list is expounded using a square bracket and the data held in it is separated by commas. A list can be changed, thus it is mutable and ordered. A list contains the following data: integers, strings, boolean etc.
Before we proceed to insert lists, here is an example of a Python list:
1
2
3
4
5
6
7
8
9
10
11
#A list with variable items
items = [12, True, "shop", 23.00]
#print the list items
print(items)
#Append a value in a list
items.append(‘products’)
#Print the list items
print(items)
Below is the result of the above lines of code:
NB: From the example above, we have added a value “products” in the list, hence we will be able to insert values to the items variable.
insert()
list methodThe Python method insert() helps to insert elements to the list to a specific index as shown in the below code:
1
2
3
4
5
6
7
8
9
10
11
#A list with variable items
items = [12, True, "shop", 23.00]
#print the list items
print(items)
#Using the insert() method to insert‘ sugar’ at index 3(4 th position)
items.insert(3, “sugar”)
#Print the List items
print(items)
The result of the above insert() method is displayed in the below image:
The list insert method()
has parameters which include:
Index parameter - The element is inserted on the index. When the index is 1 then it is the second value of the list.
Element parameter - It is inserted in the Python list.
Insert()
return valueThe list insert method returns None, but only updates the list. The process of the return value is shown below:
1
2
3
4
5
6
7
8
#Creating a list of even numbers
even_numbers = [2, 4, 6, 8]
#Insert 10 at index 4
even_numbers.insert(4, 10)
#print the even_numbers
print(even_numbers)
The list will be updated and at index 4 a value/element will be added in the list as displayed in the below output:
NB: A tuple can be inserted into a list as displayed below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#A list that is mixed
numbers = [{
3,
4
}, [6, 7, 8]]
#A tuple to be inserted
n_tuple = (4, 9)
#Insert a tuple to the list
numbers.insert(1, n_tuple)
#print the updated list
print(numbers)
The result/output of the above-inserted tuple is displayed below:
A tuple is a data type that cannot be changed (immutable) and ordered by elements. Immutable means one cannot add or remove elements. A tuple contains various data types which help in placing a sequence of values and separating them by commas, use of parentheses, and also without commas.
Example of a Python tuple:
1
2
3
4
5
6
7
8
9
10
11
#create a tuple without a parentheses
new_tuple = 23, “sample”
#print the tuple without parentheses
print(new_tuple)
#create a tuple with a parentheses
two_tuple = (66, 49, “variable”)
#print the tuple with a parentheses
print(two_tuple)
String literals are created by writing a group of characters enclosed by single (‘’), double (“”) and triple quotes. The string literal helps to specify the contents in a program with strings. Below is a sample string literal:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# string literal with single quote b1 = ‘A literal string’ #string literal with double quotes b2 = “A literal string” #string literal with triple quotes b3 = ‘’’this is the new rule’’’ #Print all the string literals print(b1) print(b2) print(b3)
NB: Strings cannot be changed (immutable). Modifying a string will result in a new copy of the string.
A Python array is a group of items that are stored at adjacent memory locations. Arrays help to keep multiple items of the same category together. An array is a special variable that stores values. Create an array by importing array modules as shown below:
1
2
3
4
5
6
7
8
9
10
11
#importing arrays
import array as arr
#create an array with integers
b = arr.array(‘j’, [2, 4, 6])
#print the original array
print(“This is an array: ”, end = ”“)
for j in range(0, 3):
print(b[j], end = ””)
print()
The output of the above code is displayed below:
Array in Python append using the append()
function
Using the append()
function helps to add elements or arrays to another array. Python lists are dynamic arrays in which the append()
function helps to add elements at the end of the list.
An example of the append()
function to the list:
1
2
3
4
5
6
7
8
listing = [10, 12, 14, 16, 18]
y = [20, 21, 23]
#append the second list to the listing
listing.append(y)
#print the list
print(listing)
How to initialize the array using the array module using the append()
function is shown below:
1
2
3
4
5
6
7
8
9
10
11
12
13
#Importing the array module
import array
#use of array module
y = array.array(‘c’, [3.4, 4.4])
z = 20
#use the append()
function
y.append(z)
#print the output
print(y)
append()
function with NumPy arrayPython NumPy module is used to generate an array and manipulate mathematical function datasets. There are various syntaxes while using the NumPy append()
function as described below:
1
numpy.append(array, value, axis)
Array - it is in which data is appended
Axis - data added to an array
Value - specific row or column operations
NB: We will use the numpy.arange() method in creating an array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#importing the numpy library
import numpy as np
x = np.arange(4)
print(x)
z = np.arange(20, 25)
print(z)
#Create a new variable and append an array
nes = np.append(x, z)
#print the result
print(nes)
The output of the above code of NumPy array is displayed below:
NOTE FOR PYTHON ARRAY:
For an array to be created, there are steps to follow:
a. Python NumPy array
b. Python array from using array module
c. Python list
A Python dictionary is a collection of data (unordered) that stores data in a format of key: value pair, in which indexing of a dictionary is done by using keys. A dictionary is identified using the curly braces {} to the data types such as tuples, strings, and numbers.
Example of Python dictionary:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#create a python dictionary with a key and a value
dict = {
‘
name’: ‘topcoder’,
1: [2, 4, 6, 8]
}
#print the dictionary
print(dict)
#How to access an element using a key
print(dict[‘name’])
#Using the get() method to access the element
print(dict.get(1))
Below is the result of the above dictionaries:
A set is a changeable (mutable) and unordered collection of elements. Sets help to test membership and eliminate duplicate entries. Sets are created using the built-in set() function method and placed in a sequence separated by commas or curly braces.
Example of creating a Python set:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#creating a set in python with the use of a string set2 = set() #print the set print(set2) #Use of a string set2 = set(“this is a string set”) print(set2) #Create a set using a constructor texts = “this is a string set” set2 = set(texts) #print the set print(set2) #Create a set using a python list set2 = set([“These”, “nice”, “shop”]) #print the set print(set2)
The output of the above code is displayed below:
Using the add()
function method to add elements in a set
Elements are added to a set using a built-in add() method. Lists cannot be added to a set because they can be changed while tuples cannot be changed (immutable). The use of add() function method is displayed below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
set2 = set()
#print the set
print(set2)
#Add elements and tuples to a set
set2.add(6)
set2.add(8)
set2.add(10, 12)
#print the set2
print(set2)
#Add elements to a set with an Iterator
for j in range((2, 8)):
set2.add(j)
print(set2) #print the addition of elements
The output of the above code is displayed below:
An item in a set can only be accessed using a for loop. The example is shown below on how items of a specified value can be accessed in a set:
1 2 3 4 5 6 7 8 9 10
#access elements in a set set2 = set([“these”, “are”, “new”]) print(set2) #Access the element using the For Loop for j in set2: print(j, end = ”“) #Check the element using a keyword print(“these” in set2)
The output of the above code is displayed below in an image:
After studying the different types of data structures such as lists, tuples, sets, dictionaries, etc., we can learn about algorithms.
The sorting algorithm is used to help sort data to a given order, which is classified as bubble sort or merge sort. A bubble sort does a comparison and sorts the adjacent elements as displayed below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#write a
function
for the bubble sort
def sort_bubble(new_list):
a = len(new_list) - 1 #the minus 1 is the iteration
for y in range(a):
for z in range(a - y):
If new_list[z] > new_list[y + 1]:
new_list[z], new_list[z + 1] = new_list[+1], new_list[y]
return new_list
new_list = [20, 2, 8, 4]
sort_bubble(new_list)
Searching algorithms help to seek elements present in a dataset. There are various types of search algorithms which include: Binary search, linear search, interpolation search, and exponential search. Example of a linear search algorithm is displayed below:
1
2
3
4
5
6
7
8
9
def linear_search(new_list, key):
for index in range(0, len(new_list)):
if (new_list[index] == key):
return index
else:
return“ not available”
new_list = [20, 2, 8, 4]
linear_search(new_list, 24)