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))
[12, 30, 7]
3Like 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")
Ada
Linus
Grace
(an empty line)Name: Ada
Name: Linus
Name: Grace
Name:
['Ada', 'Linus', 'Grace']
3 namesThe 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)
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)
['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.