Today we’ll learn how to append elements to lists using the append method.
Here’s the video version of this article:
Lists don’t have a fixed size. They can grow at runtime. You use append to add new elements:
>>> names = ['Alice', 'Bernard', 'Steve', 'Emma', 'Sam']
>>> names.append("Jenny")
>>> names
['Alice', 'Bernard', 'Steve', 'Emma', 'Sam', 'Jenny']
You also use the append method to add a list as a sublist:
>>> authors = ["Austen", ["Smith", "Garson"], "Bennet"]
>>> authors.append(["Jackson", "Warwick"])
>>> authors
['Austen', ['Smith', 'Garson'], 'Bennet', ['Jackson', 'Warwick']]
You can define empty lists. Then you can add elements to them:
>>> scores = []
>>> scores
[]
>>> scores.append(5)
>>> scores.append(14)
>>> scores
[5, 14]