Lists can be changed with several methods. What are these methods?
To add items to a list, you can use the append() method. Call the method on the list, the parameter contains the item to add. Calling append(3) would add 3 to the list. To remove an item from the end of the list, you can use the pop() method.
Lists can be accessed like traditional arrays, use the block quotes and index to get an item.
Related course: Complete Python Programming Course & Exercises
Example
Lists can be modified using their methods.
In the example below we create a list
and use methods to change the list contents.
Append and pop
Type the program shown below and run it:
1
2
3
4
5
6
7
x = [3,4,5]
x.append(6)
print(x)
x.append(7)
print(x)
x.pop()
print(x)
Access items
To access items, simply use the block quotes:
1
2
3
4
5
6
x = [3,4,5]
print(x[0])
print(x[1])
print(x[-1])
If you are a beginner, then I highly recommend this YouTube Python Playlist.
Exercise
Try the exercises below
- Given the list y = [6,4,2] add the items 12, 8 and 4.
- Change the 2nd item of the list to 3.
After completing these continue with the next exercise.