Show the core Python list operations: adding, removing, searching and ordering.
A list is an ordered, mutable sequence, and its method set covers everything you normally need to do with a collection.
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 - membership
items.sort()
print(items) # ['apple', 'cherry', 'date', 'first']
items.reverse()
print(items) # ['first', 'date', 'cherry', 'apple']
print(len(items)) # 4The order of the calls matters for the output. After append and insert the list is first, apple, banana, cherry, date; removing banana leaves first, apple, cherry, date, so index reports cherry at position 2.
Two methods that raise rather than return a default are worth knowing. remove raises ValueError if the value is not present, and index raises ValueError too. The list.index lookup and the value scan behind remove are both linear in the length of the list, which is why membership tests on a long list should use a set instead.
Two more behaviours to know. sort and reverse modify the list in place and return None, so you must not write result = items.sort() expecting a sorted list. And list.pop removes and returns an element, defaulting to the last one, so items.pop() both shortens the list and hands you the removed value — useful as a stack operation.