Show the core Python list operations: adding, removing, searching and ordering.
A list is an ordered collection that you can change, and its methods cover everything you normally need to do with a group of items.
items = ['apple', 'banana', 'cherry']
items.append('date') # add one item to the end
items.insert(0, 'first') # insert at a position
items.remove('banana') # remove the first matching value
print(items) # ['first', 'apple', 'cherry', 'date']
print(items.index('cherry')) # 2 - the position
print('date' in items) # True - is it in the list?
items.sort()
print(items) # ['apple', 'cherry', 'date', 'first']
items.reverse()
print(items) # ['first', 'date', 'cherry', 'apple']
print(len(items)) # 4
The order of the calls matters for the output. After the append and the insert the list holds first, apple, banana, cherry, and date. Removing banana leaves first, apple, cherry, and date, so index() reports that cherry sits at position 2.
Two methods raise an error instead of returning a default value, and it is worth knowing which ones. remove() raises a ValueError when the value is not in the list, and index() raises a ValueError too. Both of them look through the whole list until they find what they need, so they get slower as the list grows. That is why you should use a set when you need to check membership many times.
Two more behaviours are important. sort() and reverse() change the list in place and return None, so you must never write result = items.sort() and expect to receive a sorted list. And pop() removes an item and hands it back to you, defaulting to the last one, so items.pop() both shortens the list and gives you the removed value. That makes it a good building block for a stack.