How to Append to a List in Python
The Python programming language stores data in a variety of collections, including a list. The list collection stores a number of items that are separated by a comma. Lists are iterable objects, meaning all the items in the object can be iterated over within a function. You can also pinpoint the exact index of an item in a list and interact with it directly. Lists have many built-in functions and uses, and one of the most common functions is the append function. You can use the "append()" function to add items to the end of a list.
Things You'll Need
- Computer with Python 3.2 programming language installed (see Resource)
Open the IDLE text editor that comes with the Python programming language download package. The IDLE program is found in the "Program Files" in the Python directory. A blank source code file opens in the IDLE text editor window.
Declare a list and add some items to it. This can be done with one line of code, like this:listOfAircraft = ["Helicopter", "Plane", "Blimp"]
Append an item to the end of the list using the "append()" function. The syntax for this function looks like this:listOfAircraft.append("UFO")
Print the list. The "print()" function can automatically iterate over iterable collections, so you can just pass the entire list to "print()," and it will print out all the elements of the list. The code to do this looks like this:print(listOfAircraft)
Execute the program by pressing "F5." The program output looks like this:['Helicopter', 'Plane', 'Blimp', 'UFO']