← Python for Beginners
0 of 27 lessons done0%

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 item

Start 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:

  1. append "banana"
  2. insert "kiwi" at the start
  3. remove "apple"
  4. sort the list

At the end, fruits should be ['banana', 'kiwi', 'mango']. Print it.