Python Arena
Step 2 of 6

Adding items: append and insert

A list often starts empty and grows while the program runs. The append method adds an item to the end of a list:

scores = []
scores.append(12)
scores.append(30)
scores.append(7)
print(scores)
print(len(scores))
Output
[12, 30, 7]
3

Like upper for strings, append is a method: you write it after the list, with a dot in between. It changes the list it's called on, so scores.append(12) adds 12 to scores and to no other list.

append really shines in a loop. This program reads names until the user types an empty line:

names = []
while True:
    name = input("Name: ")
    if name == "":
        break
    names.append(name)
print(names)
print(len(names), "names")
Input
Ada
Linus
Grace
(an empty line)
Output
Name: Ada
Name: Linus
Name: Grace
Name:
['Ada', 'Linus', 'Grace']
3 names

The program doesn't need to know in advance how many names will come: the list simply grows by one item each time.

append takes exactly one item. To add two, call it twice:

scores = [12, 30]
scores.append(7, 9)
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    scores.append(7, 9)
    ~~~~~~~~~~~~~^^^^^^
TypeError: list.append() takes exactly one argument (2 given)

Adding to a given place

insert adds an item at the index you choose. It takes two arguments: first the index, then the item. The items from that index on move one place to the right:

queue = ["Ada", "Linus", "Grace"]
queue.insert(0, "Guido")
print(queue)
queue.insert(2, "Margaret")
print(queue)
Output
['Guido', 'Ada', 'Linus', 'Grace']
['Guido', 'Ada', 'Margaret', 'Linus', 'Grace']

insert(0, ...) puts an item at the very front. After the first insert, Ada moved from index 0 to index 1, so "Margaret" at index 2 lands between Ada and Linus.

Your task

Challenge 1 of 3

Fill in the blanks so the program adds milk to the end of the shopping list and bread to its start:

['bread', 'eggs', 'apples', 'milk']

Challenge 2

Write a program that reads guests' names until the user types an empty line, adding each name to a list. At the end it prints the list and the number of guests:

Guest: Ada
Guest: Linus
Guest:
['Ada', 'Linus']
2 guests

Challenge 3

Write a to-do program. It reads tasks until the user types an empty line. A task that ends with ! is urgent and goes to the start of the list; the others go to the end. Then it prints the list:

Task: wash dishes
Task: pay rent!
Task: call grandma
Task:
['pay rent!', 'wash dishes', 'call grandma']

You can assume no task is empty except the last line.