Coding for All
Lesson 16: Growing Lists
Growing Lists Add to a list and count its items.
1fruits = ["apple", "banana"]
2fruits.append("cherry")
3print(fruits)
4print(len(fruits))
Terminal
$ python3 main.py
['apple', 'banana', 'cherry']
3
Every line, explained
fruits = ["apple", "banana"]
A list stores several values in one variable. The values go between square brackets, separated by commas. Lists are one of Python's favourite tools, and unlike some languages, you can print one directly and see its contents.
fruits.append("cherry")
.append(...) adds a new item to the END of the list. The list grows from 2 items to 3.
print(fruits)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. The cherry is now in the list.
print(len(fruits))
len(...) tells you how many items are in a list (its length). len is short for length, and it works on strings too: len("hi") is 2.