Introduction
The data structure is a tool for organizing data. Not only for storage but also for solving some problems. There are some data structures in Python including list, dictionary, tuple, and set.
List
A list is a data structure that stores an item sequentially using indices. This is the illustration of the list data structure.
There are many ways to create a list in Python.
- Initialize the value directly inside a list.
items = [1,2,3,4]
- Initialize an empty list.
items = []
The item inside the list can be accessed directly via the index.
items = [1,2,3,4,5]
# access item at index 2
result = items[2]
print(result) # returns 3
All items inside the list can be retrieved using the for
loop. This is an example.
# create a new list
items = [1,2,3,4,5]
# retrieve each item inside a list
for item in items:
print(item)
Output
1
2
3
4
5
Based on the code above, the list called items
is created with assigned items. Each item is retrieved using the for
loop.
List Basic Operations
The append()
function adds a new item to a list. This is an example of append()
usage.
# create empty list
shopping_list = []
# add some items
shopping_list.append("apple")
shopping_list.append("milk")
shopping_list.append("cereal")
# retrieve all items
for item in shopping_list:
print(item)
Output
apple
milk
cereal
The append()
is illustrated in the picture below.
Besides the append()
function, the insert()
function adds a new item in a specific index. This is an example.
items = ["apple","banana","mango","coffee"]
# add new item at index 1
items.insert(1,"cereal")
# retrieve all items
for item in items:
print(item)
Output
apple
cereal
banana
mango
coffee
The insert()
is illustrated in the picture below.
Updating an item inside a list is straightforward. Just specify the index of the item then change it with the updated item.
# create a list
drinks = ["milkshake","black tea","banana milk","mango juice"]
# update value at index 2
drinks[2] = "chocolate milk"
print(f"value at index 2: {drinks[2]}")
Output
value at index 2: chocolate milk
The remove()
function removes an item from the list. This is an example.
items = ["apple","banana","mango","coffee"]
# remove "mango"
items.remove("mango")
# remove item at index 1
items.remove(items[1])
print("after removed")
for item in items:
print(item)
Output
after removed
apple
coffee
The items inside a list can be selected by specifying the start index and end index of the list. This is the basic structure for selecting items in a list.
list_name[start:end]
The items are selected from the start
index up to but not including the end
index. This is an example of selecting items in a list.
items = ["apple","mango","papaya","coconut","banana"]
# select items from index 1 up to but not including index 3
selected = items[1:3]
# show all items
print(f"all items: {items}")
# show the selected items
print(f"selected: {selected}")
Output
all items: ['apple', 'mango', 'papaya', 'coconut', 'banana']
selected: ['mango', 'papaya']
List Comprehension
List comprehension is a "functional" way to create a list. To understand list comprehension, let's take a look at an example of creating a list that contains even values using an iterative approach.
evens = []
for i in range(1,11):
evens.append(i*2)
print(evens)
Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Based on the code above, the even numbers are generated using the iterative approach with a for
loop. The example above can be achieved also using list comprehension. This is an example of generating even numbers using list comprehension.
evens = [x*2 for x in range(1,11)] # using list comprehension
print(evens)
Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Based on the code above, the list comprehension approach provides more concise code and the same result as the previous iterative approach.
The list comprehension can be used together with if
branching. In this example, list comprehension is used to filter certain values based on the specific condition.
samples = [12,32,55,10,2,57,66]
result = [s for s in samples if s % 4 == 0] # using list comprehension
print(result)
Output
[12, 32]
This is the iterative version of the previous example.
samples = [12,32,55,10,2,57,66]
result = []
for s in samples:
if s % 4 == 0:
result.append(s)
print(result)
Multi-Dimensional List
The list can be stored in a multi-dimensional approach like a matrix. This is an example of declaring a multi-dimensional list for storing a number matrix.
matrix = [
[1,2,3],
[4,5,6],
[7,8,9],
]
The item can be accessed with double square brackets ([x][y]
) by specifying the x
that represents the index of the main list whilst y
represents the index of the item inside the nested list. This is the illustration of the number matrix.
The items inside the multi-dimensional list can be retrieved by utilizing a nested for loop.
matrix = [
[1,2,3],
[4,5,6],
[7,8,9],
]
# retrieve all items
for m in matrix:
for num in m:
print(num)
Output
1
2
3
4
5
6
7
8
9
Dictionary
The dictionary is a data structure that stores records as key-value pairs. Each key must be unique, while duplicate values are permitted. This illustrates the dictionary data structure:
There are many ways to create a dictionary:
- Create a dictionary with initialized records.
courses = {
"C001":"Algorithm",
"C002":"Data Structure",
"C003":"Programming in Python",
}
- Create an empty dictionary.
courses = {}
All records inside the dictionary can be retrieved using the for
loop. This is an example.
# create a dictionary
courses = {
"C001":"Algorithm",
"C002":"Data Structure",
"C003":"Programming in Python",
}
# retrieve all items
# "k" represents item's key
# "v" represents item's value
for k, v in courses.items():
print(k,v)
Output
C001 Algorithm
C002 Data Structure
C003 Programming in Python
Dictionary Basic Operations
To insert a new item inside a dictionary, specify the key-value pair of the item. Make sure the key is unique.
map_name['key'] = value
This is an example of inserting a new item inside the dictionary.
# create an empty dictionary
courses = {}
# insert courses
courses['C001'] = 'Algorithm'
courses['C002'] = 'Data Engineer'
courses['C003'] = 'Data Science'
# retrieve all courses
for k, v in courses.items():
print(k,v)
Output
C001 Algorithm
C002 Data Engineer
C003 Data Science
To update an item inside the dictionary, specify the key of the item then insert the updated value.
courses = {
"C001":"Algorithm",
"C002":"Data Engineer",
"C003":"Data Science",
}
print(f"before update: {courses['C002']}")
# update course with key equals to C002
courses['C002'] = "Data Analyst"
print(f"after update: {courses['C002']}")
Output
before update: Data Engineer
after update: Data Analyst
The keys and values in the dictionary can be accessed independently using different methods.
courses = {
"C001":"Algorithm",
"C002":"Data Engineer",
"C003":"Data Science",
}
# retrieve keys
course_keys = courses.keys()
print(f"keys: {course_keys}")
# retrieve values
course_values = courses.values()
print(f"values: {course_values}")
Output
keys: dict_keys(['C001', 'C002', 'C003'])
values: dict_values(['Algorithm', 'Data Engineer', 'Data Science'])
The pop()
method removes the item from the dictionary based on the given key.
courses = {
"C001":"Algorithm",
"C002":"Data Engineer",
"C003":"Data Science",
}
# remove course with key equals to C003
courses.pop('C003')
for k, v in courses.items():
print(k,v)
Output
C001 Algorithm
C002 Data Engineer
The clear()
method removes all items inside the dictionary.
courses = {
"C001":"Algorithm",
"C002":"Data Engineer",
"C003":"Data Science",
}
# remove all items
courses.clear()
# check if the dictionary is empty
is_empty = len(courses.values()) == 0
print(is_empty)
Output
True
Tuple
The tuple is an immutable data structure for storing many values. The tuple may contain mutable values. There are two ways to create a new tuple.
- Create a tuple with assigned values.
# create a tuple with assigned values
fruits = ("apple","banana","mango")
# retrieve all values
for f in fruits:
print(f)
Output
apple
banana
mango
- Create an empty tuple.
# create an empty tuple
fruits = ()
Tuple Basic Operations
A tuple is immutable, which means that its values cannot be changed or updated once it has been created.
# create a tuple with assigned values
fruits = ("apple","banana","mango")
# error, tuple is immutable
fruits[0] = "starfruit"
The values from the tuple can be retrieved using "tuple unpacking" (this concept is similar to object destructuring in JavaScript).
When unpacking, the size of the unpacked values must equal the size of the tuple.
# create a tuple with assigned values
fruits = ("apple","banana","mango")
# tuple unpacking
(one, two, three) = fruits
print(one,two,three)
Output
apple banana mango
Set
A set is an unordered data structure that only contains unique items. There are many ways to create a set.
# create a set with assigned values
data = {1,2,3,4}
# create a set with set() function
records = set(['milk','coffee','juice'])
The empty set can be created using the set()
function.
empty_set = set()
The set data structure removes duplicate values automatically.
# create a set with assigned values
data = {1,1,1,2,2,2,3,3,4,5,4}
for d in data:
print(d)
Output
1
2
3
4
5
The values inside the set can be accessed using the for
loop.
# create a set with assigned values
data = {1,2,3,4}
for d in data:
print(d)
Output
1
2
3
4
Set Basic Operations
The set data structure provides many operations like union, intersection, difference, and symmetric difference.
The union operation returns all items in both sets.
data1 = {'burger','kebab','noodle','pasta','pizza'}
data2 = {'burger','french fries','pasta','cereal','biscuit'}
result = data1 | data2
print(result)
Output
{'burger', 'cereal', 'french fries', 'noodle', 'kebab', 'pizza', 'pasta', 'biscuit'}
The intersection operation returns all items that exist in the intersection of the sets.
data1 = {'burger','kebab','noodle','pasta','pizza'}
data2 = {'burger','french fries','pasta','cereal','biscuit'}
result = data1 & data2
print(result)
Output
{'burger', 'pasta'}
The difference operation returns all items that only exist in a certain set.
data1 = {'burger','kebab','noodle','pasta','pizza'}
data2 = {'burger','french fries','pasta','cereal','biscuit'}
result = data1 - data2 # items in data1 but no in data2
print(result)
Output
{'pizza', 'kebab', 'noodle'}
The symmetric difference operation returns all items that exist in either of the sets, but not in the intersection.
data1 = {'burger','kebab','noodle','pasta','pizza'}
data2 = {'burger','french fries','pasta','cereal','biscuit'}
result = data1 ^ data2 # items in data1 or data2 but not both
print(result)
Output
{'biscuit', 'kebab', 'cereal', 'pizza', 'noodle', 'french fries'}
Introduction to Function
The function is a callable unit containing instructions, aimed at reducing code duplication and organizing complex tasks. There are two types: void functions (no return value) and those that return a value.
This is the basic structure of function in Python.
def function_name(args):
function body
This is the example of void function (no return value) in Python.
# create a function
def hello():
print("hello!")
# call the function
hello()
Output
hello!
Based on the code above, the function called hello()
is created. The function is called by specifying the function name followed with parentheses ()
.
This is the example of function with return value.
# create a function with return value
def add(a,b):
return a + b
result = add(2,4)
print(result)
Output
6
Based on the code above, the function called add()
is created to sum two numbers. The return value of add()
function is stored inside result
variable.
When working with the return value function, ensure the returned value is being used.
The topic of functions in Python will be explained in detail in a separate chapter.
Example - Simple Todo List Application
Let's create a simple todo list application. This application uses list as a storage for todos and utilizes function for a cleaner code.
The first step is to import uuid
package and create a list called todos
for storing todo records. The uuid
package is used as an identifier (ID) for todo record.
import uuid
# create a local storage for storing todos
todos = []
After that, create a view_todos()
function to retrieve all todo records. All todo records are retrieved using for
loop.
def view_todos():
"""
view all todos
"""
print("all todos")
for todo in todos:
print("====")
print(f"id: {todo["id"]}")
print(f"title: {todo["title"]}")
print("====")
Create a view_todo()
function to retrieve todo record by specified ID. Each todo record is checked inside the for
loop to check if the current todo ID is equal to the specified ID. If matches, then the todo record is displayed.
def view_todo(todo_id):
"""
view todo by ID
"""
for todo in todos:
if todo["id"] == todo_id:
print("====")
print(f"id: {todo["id"]}")
print(f"title: {todo["title"]}")
print("====")
Create a create_todo()
function to create a new todo. The todo record is represented as a dictionary with id
and title
field.
def create_todo(todo_input):
"""
create a new todo
"""
new_todo = {
"id":uuid.uuid4().hex,
"title":todo_input
}
todos.append(new_todo)
print("todo added!")
Create a update_todo()
function to update a todo. In this function, the todo record is updated by specified ID.
def update_todo(todo_id,todo_input):
"""
update existing todo
"""
for todo in todos:
if todo["id"] == todo_id:
todo["title"] = todo_input
print("todo updated!")
Create a delete_todo()
function to delete a todo. In this function, the todo record is deleted by specified ID.
def delete_todo(todo_id):
"""
delete todo
"""
for todo in todos:
if todo["id"] == todo_id:
todos.remove(todo)
print("todo deleted!")
Finally, create a function called display_menu()
to display the main menu of the application.
def display_menu():
"""
displays the main menu of the application
"""
# create a variable for storing user's choice
choice = 0
while choice != 6:
print("Simple Todo App")
print("1. view all todos")
print("2. view todo by ID")
print("3. create a new todo")
print("4. update todo")
print("5. delete todo")
print("6. exit")
print("---------------")
choice = int(input("insert choice: "))
match choice:
case 1:
view_todos()
case 2:
todo_id = input("insert todo ID: ")
view_todo(todo_id)
case 3:
todo_input = input("insert new todo: ")
create_todo(todo_input)
case 4:
todo_id = input("insert todo ID: ")
todo_input = input("insert updated todo: ")
update_todo(todo_id,todo_input)
case 5:
todo_id = input("insert todo ID: ")
delete_todo(todo_id)
case 6:
print("good bye")
case _:
print("invalid choice, please input 1-6")
# call the function
display_menu()
This is the complete code.
import uuid
# create a local storage for storing todos
todos = []
def view_todos():
"""
view all todos
"""
print("all todos")
for todo in todos:
print("====")
print(f"id: {todo["id"]}")
print(f"title: {todo["title"]}")
print("====")
def view_todo(todo_id):
"""
view todo by ID
"""
for todo in todos:
if todo["id"] == todo_id:
print("====")
print(f"id: {todo["id"]}")
print(f"title: {todo["title"]}")
print("====")
def create_todo(todo_input):
"""
create a new todo
"""
new_todo = {
"id":uuid.uuid4().hex,
"title":todo_input
}
todos.append(new_todo)
print("todo added!")
def update_todo(todo_id,todo_input):
"""
update existing todo
"""
for todo in todos:
if todo["id"] == todo_id:
todo["title"] = todo_input
print("todo updated!")
def delete_todo(todo_id):
"""
delete todo
"""
for todo in todos:
if todo["id"] == todo_id:
todos.remove(todo)
print("todo deleted!")
def display_menu():
"""
displays the main menu of the application
"""
# create a variable for storing user's choice
choice = 0
while choice != 6:
print("Simple Todo App")
print("1. view all todos")
print("2. view todo by ID")
print("3. create a new todo")
print("4. update todo")
print("5. delete todo")
print("6. exit")
print("---------------")
choice = int(input("insert choice: "))
match choice:
case 1:
view_todos()
case 2:
todo_id = input("insert todo ID: ")
view_todo(todo_id)
case 3:
todo_input = input("insert new todo: ")
create_todo(todo_input)
case 4:
todo_id = input("insert todo ID: ")
todo_input = input("insert updated todo: ")
update_todo(todo_id,todo_input)
case 5:
todo_id = input("insert todo ID: ")
delete_todo(todo_id)
case 6:
print("good bye")
case _:
print("invalid choice, please input 1-6")
# call the function
display_menu()
This is the output of the application.
Sources
I hope this article helps you learn Python. If you have any feedback, please let me know in the comment section.
Top comments (0)