A list is a special Python class that can be used to store multiple data entries in one variable.
fruits = ['apple', 'banana', 'coconut']
This creates a list fruits
with three strings containing different fruits.
The individual elements can be printed using indexing, which starts from zero:
print(fruits[1]) # output: banana
Index notation can also be used to overwrite elements of a list:
fruits[2] = 'cherry'
print(fruits) # output is ['apple', 'banana', 'cherry']
To add elements to the end of the list, use the append
method:
fruits.append('fig')
print (fruits) # output: ['apple', 'banana', 'coconut', 'fig']
In this way, the list fruits
is modified in place.
It is wrong to use an assignment such as fruits = fruits.append('fig')
.
Here are some other methods that can be used to modify Python lists in place:
Method |
Description |
append(x) |
Add an item to the end of the list |
clear() |
Remove all items from the list |
copy() |
Return a shallow copy of the list |
count(x) |
Return the number of occurrences of x |
index(x[,start[,end]]) |
Return first index of x |
insert(i, x) |
Insert x at position i |
pop([i]) |
Remove and return item at index i (default last) |
remove(x) |
Remove first occurrence of x |
reverse() |
Reverse the list in place |