Learning Objectives
- Understand how to Create, Read, Update & Delete elements of a list with the various Python methods & special syntax
Working with Lists (CRUD)
In order to build more complex applications, we need to understand how to perform the 4 main operations of handling data:
- Create
- Read
- Update
- Delete
Creating a List
A list can store multiple elements of different datatypes where all element are wrapped in a square bracket and separated by commas:
hobbies = ['basketball', 'badminton', 'cricket']Reading a List
We can access different elements of list by using something similar to index numbers.
The first element of a list is given the index number of 0
The second element of a list is given the index number of 1 and so on...
The last element of a list is given the index number of (n - 1) where n stands for the number of element in the list
hobbies = ['basketball', 'badminton', 'cricket']
print(hobbies[0])
print(hobbies[1])Output:
basketball
badmintonUpdating a list
Methods:
Methods are built-in functions for a specific datatype!
They are used after the variable name followed by a . then the name of the method. (e.g. hobbies.insert() and hobbies.append())
Insert Method
We can also add additional elements to the list using the .insert() method after the variable name storing the list.
The .insert() method takes in two arguments: position (index number of where you want your data to be added) and element (data)
hobbies = ['basketball', 'badminton', 'cricket']
hobbies.insert(0, 'dancing')
print(hobbies)Output:
['dancing', 'basketball', 'badminton', 'cricket']Append Method
We can also add elements to the back of the list with the special .append() method as follows:
hobbies = ['basketball', 'badminton', 'cricket']
hobbies.append('dancing')
print(hobbies)Output:
['basketball', 'badminton', 'cricket', 'dancing']Deleting a list
There are two main ways to delete elements in a list, using either the .remove() or the .pop() method.
Remove Method
The .remove() method takes in one argument which is the value of what we want to delete.
hobbies = ['basketball', 'badminton', 'cricket']
hobbies.remove('basketball')
print(hobbies)Output:
['badminton', 'cricket']Pop Method
The .pop() method takes in one argument which is the index (number) of the element we want to delete:
hobbies = ['basketball', 'badminton', 'cricket']
hobbies.pop(1)
print(hobbies)Output:
['basketball', 'cricket']Pop Trick
If no argument is passed, .pop() will automatically remove the last element in the list