DEV Community

nadirbasalamah
nadirbasalamah

Posted on

Python Tutorial - 3 Data Structure

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.

List in Python Illustration

There are many ways to create a list in Python.

  1. Initialize the value directly inside a list.
items = [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode
  1. Initialize an empty list.
items = []
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

apple
milk
cereal
Enter fullscreen mode Exit fullscreen mode

The append() is illustrated in the picture below.

append illustration

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)
Enter fullscreen mode Exit fullscreen mode

Output

apple
cereal
banana
mango
coffee
Enter fullscreen mode Exit fullscreen mode

The insert() is illustrated in the picture below.

insert illustration

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]}")
Enter fullscreen mode Exit fullscreen mode

Output

value at index 2: chocolate milk
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

after removed
apple
coffee
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Output

all items: ['apple', 'mango', 'papaya', 'coconut', 'banana']
selected: ['mango', 'papaya']
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

[12, 32]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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],
]
Enter fullscreen mode Exit fullscreen mode

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.

matrix in Python

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)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
6
7
8
9
Enter fullscreen mode Exit fullscreen mode

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:

dictionary illustration in Python

There are many ways to create a dictionary:

  1. Create a dictionary with initialized records.
courses = {
    "C001":"Algorithm",
    "C002":"Data Structure",
    "C003":"Programming in Python",
}
Enter fullscreen mode Exit fullscreen mode
  1. Create an empty dictionary.
courses = {}
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

Output

C001 Algorithm
C002 Data Structure
C003 Programming in Python
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

C001 Algorithm
C002 Data Engineer
C003 Data Science
Enter fullscreen mode Exit fullscreen mode

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']}")
Enter fullscreen mode Exit fullscreen mode

Output

before update: Data Engineer
after update: Data Analyst
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Output

keys: dict_keys(['C001', 'C002', 'C003'])
values: dict_values(['Algorithm', 'Data Engineer', 'Data Science'])
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

C001 Algorithm
C002 Data Engineer
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

True
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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)
Enter fullscreen mode Exit fullscreen mode

Output

apple
banana
mango
Enter fullscreen mode Exit fullscreen mode
  1. Create an empty tuple.
# create an empty tuple
fruits = ()
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

apple banana mango
Enter fullscreen mode Exit fullscreen mode

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'])
Enter fullscreen mode Exit fullscreen mode

The empty set can be created using the set() function.

empty_set = set()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
Enter fullscreen mode Exit fullscreen mode

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.

union illustration

data1 = {'burger','kebab','noodle','pasta','pizza'}
data2 = {'burger','french fries','pasta','cereal','biscuit'}

result = data1 | data2

print(result)
Enter fullscreen mode Exit fullscreen mode

Output

{'burger', 'cereal', 'french fries', 'noodle', 'kebab', 'pizza', 'pasta', 'biscuit'}
Enter fullscreen mode Exit fullscreen mode

The intersection operation returns all items that exist in the intersection of the sets.

intersection

data1 = {'burger','kebab','noodle','pasta','pizza'}
data2 = {'burger','french fries','pasta','cereal','biscuit'}

result = data1 & data2

print(result)
Enter fullscreen mode Exit fullscreen mode

Output

{'burger', 'pasta'}
Enter fullscreen mode Exit fullscreen mode

The difference operation returns all items that only exist in a certain set.

difference

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)
Enter fullscreen mode Exit fullscreen mode

Output

{'pizza', 'kebab', 'noodle'}
Enter fullscreen mode Exit fullscreen mode

The symmetric difference operation returns all items that exist in either of the sets, but not in the intersection.

symmetric difference

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)
Enter fullscreen mode Exit fullscreen mode

Output

{'biscuit', 'kebab', 'cereal', 'pizza', 'noodle', 'french fries'}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

This is the example of void function (no return value) in Python.

# create a function
def hello():
    print("hello!")

# call the function
hello()
Enter fullscreen mode Exit fullscreen mode

Output

hello!
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

6
Enter fullscreen mode Exit fullscreen mode

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 = []
Enter fullscreen mode Exit fullscreen mode

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("====")
Enter fullscreen mode Exit fullscreen mode

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("====")
Enter fullscreen mode Exit fullscreen mode

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!")
Enter fullscreen mode Exit fullscreen mode

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!")
Enter fullscreen mode Exit fullscreen mode

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!")
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()

Enter fullscreen mode Exit fullscreen mode

This is the output of the application.

todo app demo

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)