CRUD Operations on a List
- Create: Use a
for loop to add numbers from 1 to 10 into the list.
- Read: Print the list to view its contents.
- Update: Modify the value at a specific index (e.g., set the value at index 0 to 2).
- Delete: Use
pop() to remove the last element or pop(index) to remove an element at a specific index.
listA = []
#create items 1 - 10 in listA using for loop
for i in range(10):
listA.append(i+1)
#read - find index of 3 in listA
print(listA)
#update - change value at an index in listA
listA[0] = 2
print(listA)
#delete - remove a value from the list
listA.pop() #deletes last value by default
print(listA)
listA.pop(0) #deletes a value at an index
print(listA)
---------------------------------------
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
CRUD Operations on a Fixed-Size Array
- In A-Levels, we do not use a real array data structure as seen in other programming contexts.
- Instead, we simulate arrays using Python's
list data type.
- The fixed size of an array is represented by initializing a list with a specific number of
None elements.
- Operations like inserting, reading, updating, and deleting values can be performed on this simulated array.
- This approach helps in understanding the basic functionality of arrays without relying on external libraries or native array structures.
- Create: Initialize an array with a fixed size (5) filled with
None.
- Insert: Use a
for loop to add values 1 to 5 into the array.
- Read: Print the array to view its current contents.
- Update: Modify the value at a specific index (e.g., set index 0 to
99).
- Delete: Simulate removal by setting the last or specific index to
None.
# Create an array
size = 5 # the array can only store 5 variables
arr = [None] * size
# Create items 1 - 5 in arr using a for loop
for i in range(5):
arr[i] = i + 1
# Read - Print the array
print(arr)
# Update - Change value at index 0
arr[0] = 99
print(arr)
# Delete - Remove the last element by setting it to None
arr[-1] = None
print(arr)
# Delete - Remove the value at index 0
arr[0] = None
print(arr)
---------------------------------------
[1, 2, 3, 4, 5]
[99, 2, 3, 4, 5]
[99, 2, 3, 4, None]
[None, 2, 3, 4, None]