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]


