How to Append a List in Python
Python is a popular programming language that comes with a wide range of features to deal with lists. Lists are used to store multiple items in a single variable, making it easier to manipulate and work with data. If you are a Python programmer, you have probably encountered situations where you need to add new items to an existing list. This is where the append() function comes in. In this article, we will discuss how to append a list in Python.
What is List in Python?
A list is one of the built-in data structures in Python that can hold an ordered collection of items. A list can store a combination of different data types such as integers, floats, strings, and even other lists. Lists are mutable, meaning you can modify them after they have been created.
How to Create a List
Before we jump into the append() function, it is essential to know how to create a list in Python. There are two ways to create a list:
1. Using square brackets []
list_name = [item_1, item_2, item_3, …, item_n]
For example, the following code creates a list of integers:
ages = [20, 22, 23, 25, 26, 30]
2. Using the list() function
list_name = list(iterable)
For example, the following code creates a list of strings:
names = list((“John”, “Peter”, “Sara”))
How to Append a List in Python
Appending a list means adding new items to an existing list. To add an item to a list, we use the append() function, which adds the item to the end of the list. Here is the syntax of the append() method:
list_name.append(item)
For example, let’s say we have an existing list of colors:
colors = [‘red’, ‘green’, ‘blue’]
We can append a new color, say ‘yellow,’ to the end of the list using append():
colors.append(‘yellow’)
Now, our colors list will have ‘yellow’ at the end:
[‘red’, ‘green’, ‘blue’, ‘yellow’]
If we want to append more than one item to the list, we can use the extend() method. The extend() function takes an iterable (list, tuple, set, etc.) as an argument and adds each item to the end of the list.
For example, let’s create a second list of colors to append to the first list:
more_colors = [‘orange’, ‘purple’, ‘pink’]
We can extend our original list with the second list using extend():
colors.extend(more_colors)
Now, our colors list will have all the additional colors at the end:
[‘red’, ‘green’, ‘blue’, ‘yellow’, ‘orange’, ‘purple’, ‘pink’]
Conclusion
Appending a list in Python is a simple and efficient way of adding new items to an existing list. The append() method adds a single item to the end of a list, while the extend() method adds multiple items to the end of a list. Knowing how to append a list in Python is a fundamental skill for any Python programmer, and it’s a process you’ll carry out often when dealing with lists in Python.