Home >Backend Development >Python Tutorial >Python Tutorial - ata Structure
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.
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.
items = [1,2,3,4]
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.
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 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
items = [1,2,3,4]
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.
items = []
Output
items = [1,2,3,4,5] # access item at index 2 result = items[2] print(result) # returns 3
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.
# 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
This is the iterative version of the previous example.
# 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)
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.
apple milk cereal
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.
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 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 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]}")
value at index 2: chocolate milk
All records inside the dictionary can be retrieved using the for loop. 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
To insert a new item inside a dictionary, specify the key-value pair of the item. Make sure the key is unique.
list_name[start:end]
This is an example of inserting a new item inside the dictionary.
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']
To update an item inside the dictionary, specify the key of the item then insert the updated value.
evens = [] for i in range(1,11): evens.append(i*2) print(evens)
Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
The keys and values in the dictionary can be accessed independently using different methods.
evens = [x*2 for x in range(1,11)] # using list comprehension print(evens)
Output
items = [1,2,3,4]
The pop() method removes the item from the dictionary based on the given key.
items = []
Output
items = [1,2,3,4,5] # access item at index 2 result = items[2] print(result) # returns 3
The clear() method removes all items inside the dictionary.
# 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
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 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
items = ["apple","banana","mango","coffee"] # add new item at index 1 items.insert(1,"cereal") # retrieve all items for item in items: print(item)
A tuple is immutable, which means that its values cannot be changed or updated once it has been created.
apple cereal banana mango coffee
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 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
A set is an unordered data structure that only contains unique items. There are many ways to create a set.
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)
The empty set can be created using the set() function.
after removed apple coffee
The set data structure removes duplicate values automatically.
list_name[start:end]
Output
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}")
The values inside the set can be accessed using the for loop.
all items: ['apple', 'mango', 'papaya', 'coconut', 'banana'] selected: ['mango', 'papaya']
Output
evens = [] for i in range(1,11): evens.append(i*2) print(evens)
The set data structure provides many operations like union, intersection, difference, and symmetric difference.
The union operation returns all items in both sets.
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Output
evens = [x*2 for x in range(1,11)] # using list comprehension print(evens)
The intersection operation returns all items that exist in the intersection of the sets.
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Output
samples = [12,32,55,10,2,57,66] result = [s for s in samples if s % 4 == 0] # using list comprehension print(result)
The difference operation returns all items that only exist in a certain set.
[12, 32]
Output
samples = [12,32,55,10,2,57,66] result = [] for s in samples: if s % 4 == 0: result.append(s) print(result)
The symmetric difference operation returns all items that exist in either of the sets, but not in the intersection.
matrix = [ [1,2,3], [4,5,6], [7,8,9], ]
Output
items = [1,2,3,4]
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.
items = []
This is the example of void function (no return value) in Python.
items = [1,2,3,4,5] # access item at index 2 result = items[2] print(result) # returns 3
Output
# create a new list items = [1,2,3,4,5] # retrieve each item inside a list for item in items: print(item)
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.
1 2 3 4 5
Output
# 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)
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.
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.
apple milk cereal
After that, create a view_todos() function to retrieve all todo records. All todo records are retrieved using for loop.
items = ["apple","banana","mango","coffee"] # add new item at index 1 items.insert(1,"cereal") # retrieve all items for item in items: print(item)
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.
apple cereal banana mango coffee
Create a create_todo() function to create a new todo. The todo record is represented as a dictionary with id and title field.
# 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]}")
Create a update_todo() function to update a todo. In this function, the todo record is updated by specified ID.
value at index 2: chocolate milk
Create a delete_todo() function to delete a todo. In this function, the todo record is deleted by specified ID.
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)
Finally, create a function called display_menu() to display the main menu of the application.
after removed apple coffee
This is the complete code.
list_name[start:end]
This is the output of the application.
I hope this article helps you learn Python. If you have any feedback, please let me know in the comment section.
The above is the detailed content of Python Tutorial - ata Structure. For more information, please follow other related articles on the PHP Chinese website!