Collections · Lesson 17 of 27
List methods
Lists have methods to add, remove and arrange items:
fruits = ["mango", "apple"]
fruits.append("banana") # add at the end → ['mango', 'apple', 'banana']
fruits.insert(0, "kiwi") # add at index 0 → ['kiwi', 'mango', 'apple', 'banana']
fruits.remove("apple") # remove by value → ['kiwi', 'mango', 'banana']
last = fruits.pop() # remove the last item and give it back → 'banana'
fruits.sort() # sort A→Z (or small→big for numbers)
fruits.reverse() # reverse the order
print(fruits.index("kiwi")) # position of an itemStart with an empty list and fill it in a loop. This pattern is everywhere:
squares = []
for i in range(1, 4):
squares.append(i * i)
print(squares) # [1, 4, 9]Your task
Start with fruits = ["mango", "apple"]. Then:
- append
"banana" - insert
"kiwi"at the start - remove
"apple" - sort the list
At the end, fruits should be ['banana', 'kiwi', 'mango']. Print it.